WPF Notes

Why is 'StringFormat' malfunctioning?

About Data Type

If you are binding a string value to text property of TextBlock or TextBox, then append StringFormat, it will work.
For example: <TextBlock Text="{Binding StringValue, StringFormat={} I am special: {0}}" />
Otherwise, let's say if there's a object value is bound to text, it won't work at all. In this situation, you need a Converter to solve.

Decimal Type

If you are binding a string value to text property and the StringFormat is like: {}{0:N0}(formatted number), it won't work either. This also won't work in c# code like string.Format("{0:n0}", value)(if value is astring)

Why does my UI text blurry after apply DropShadowEffect?

  • Solution 1: Separate Control which applied DropShadowEffect from your text Control.
  • Solution 2: Add RenderingBias="Quality" attribute to DropShadowEffect. See ref
  • Solution 3: DropShadowEffect may cause performance issue, try SystemDropShadowChrome instead:
    • Add reference to project: PresentationFramework.Aero
    • Add using: xmlns:dropShadow="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero"

How to debug codes in design mode?

Here are the steps to debug a control at design time:

Start a second instance of Visual Studio
Attach to the first instance(vs designer is called XDesProc.exe) from the Debug menu
In the second instance, open the source code of your control
Set breakpoints at appropriate locations
In the first VS instance, reload the designer

Note that this technique isn't limited to controls; you can also use it to debug VS extensions, or anything that executes within Visual Studio.

see ref

How to binding control events to commands

<i:Interaction.Triggers>
    <i:EventTrigger EventName="OnLoaded">
        <i:EventTrigger.Actions>
            <i:InvokeCommandAction Command="{Binding MyCommand}"></i:InvokeCommandAction>
        </i:EventTrigger.Actions>
    </i:EventTrigger>
</i:Interaction.Triggers>

How to use async command execute

private async void MyCommandExecute()
{
    IsBusy = true;
    var models = await Task.Run(() =>
    {
        return GetDataFromServer();
    });
    IsBusy = false;
}

or in a better way, encapsulate DoWork method in ViewModelBase:

ViewModelBase.cs
rprc IsBusy;
public async void DoProgressAsync<TResult>(Func<TResult> workFunc, Action<TResult> callbackAction)
{
    IsBusy = true;
    var result = await Task.Run(workFunc);
    callbackAction(result);
    IsBusy = false;
}

Events for Switch TextBlock to TextBox when mousedown

Here is fields and properties in the custom control we need: _isMouseDown; IsEditMode(dependency property)

public override void OnApplyTemplate()
{
    _textblock.PreviewMouseLeftButtonDown += delegate { _isMouseDown = true; };
    _textblockv.PreviewMouseLeftButtonUp += delegate {
        if(_isMouseDown) {
          IsEditMode = true;
          Keyboard.Focus(_textBox);
          _isMouseDown = false;
        }
    };
    _label.GotKeyboardFocus += delegate{
       //same as left button up
    };
    _textBox.LostKeyboardFocus += delegate {
        IsEditMode = false;
    };
}

Simple Loading Ellipse

<ControlTemplate x:Key="LoadingControlTemplate">
        <Ellipse StrokeThickness="2" Width="12" Height="12" RenderTransformOrigin="0.5 0.5" ToolTip="{TemplateBinding ToolTip}" Name="el">
            <Ellipse.Stroke>
                <RadialGradientBrush GradientOrigin="0.2 0" Center="0.5 0.9"  RadiusX="0.75" RadiusY="0.5">
                    <GradientStop Color="Transparent" Offset="1" />
                    <GradientStop Color="White" Offset="0.35" />
                </RadialGradientBrush>
            </Ellipse.Stroke>
            <Ellipse.RenderTransform>
                <RotateTransform Angle="0" />
            </Ellipse.RenderTransform>
        </Ellipse>
        <ControlTemplate.Triggers>
            <Trigger Property="Visibility" Value="Visible">
                <Trigger.EnterActions>
                    <BeginStoryboard Name="ani">
                        <Storyboard>
                            <DoubleAnimation Storyboard.TargetProperty="(Ellipse.RenderTransform).(RotateTransform.Angle)"
                                             Storyboard.TargetName="el"
                                             To="360" Duration="0:0:0.75" RepeatBehavior="Forever" />
                        </Storyboard>
                    </BeginStoryboard>
                </Trigger.EnterActions>
                <Trigger.ExitActions>
                    <RemoveStoryboard BeginStoryboardName="ani"/>
                </Trigger.ExitActions>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>

Solid color style ProgressBar

for Indeterminate

<!--Please use Foreground as Indicator color-->
<ControlTemplate x:Key="IndeterminateProgressBar" TargetType="{x:Type ProgressBar}" >
    <Grid MinHeight="2" MinWidth="150" Name="TemplateRoot" SnapsToDevicePixels="True" >
        <Rectangle RadiusX="2" RadiusY="2" Fill="Transparent" />
        <Border CornerRadius="0" Margin="1">
            <Border.Background>
                <SolidColorBrush Color="Transparent"/>
            </Border.Background>
        </Border>
        <Border BorderThickness="0" BorderBrush="Transparent" Margin="1">
            <Border.Background>
                <SolidColorBrush Color="Transparent"/>
            </Border.Background>
        </Border>
        <Rectangle Name="PART_Track" Margin="1" />
        <Decorator Name="PART_Indicator" Margin="1" HorizontalAlignment="Left">
            <Grid Name="Foreground">
                <Rectangle Fill="Transparent" Name="Indicator" />
                <Grid Name="Animation" ClipToBounds="True">
                    <Border Name="PART_GlowRect" Width="80"  Margin="0,0,0,0" HorizontalAlignment="Left" Background="{TemplateBinding Foreground}"/>
                </Grid>
                <Grid Name="Overlay">
                </Grid>
            </Grid>
        </Decorator>
        <Border BorderThickness="0" CornerRadius="0" BorderBrush="Transparent" />
    </Grid>
</ControlTemplate>

for Determinate

<!--Please use Foreground as Indicator color, Background as TotalWidth background-->
<ControlTemplate x:Key="DeterminateProgressBar" TargetType="{x:Type ProgressBar}">
    <Grid MinHeight="2" MinWidth="150" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
        <Border x:Name="PART_Track" BorderThickness="0">
        </Border>
        <Border x:Name="PART_Indicator" BorderThickness="0" HorizontalAlignment="Left" Background="{TemplateBinding Foreground}" Margin="0">
        </Border>
    </Grid>
</ControlTemplate>

Usage

<ProgressBar Template="{StaticResource IndeterminateProgressBar}" IsIndeterminate="True" Foreground="LightBlue" 
              Visibility="{Binding IsRefreshing, Converter={StaticResource BooleanToVisibilityConverter}}"/>
<ProgressBar Template="{StaticResource DeterminateProgressBar}" Minimum="0" Maximum="{Binding ItemCount}" Value="{Binding CurrentItemIndex}" Foreground="Red" Background="Green"
              Visibility="{Binding IsLoadingFinished, Converter={StaticResource BooleanToVisibilityConverter}}"/>

**for 30 seconds pending progress

A little trick using rectangle by scale animation rather than ProgressBar with Timer:

<Style x:Key="PendingProgressRect" TargetType="Rectangle">
        <Setter Property="Height" Value="1"/>
        <Setter Property="HorizontalAlignment" Value="Stretch"/>
        <Setter Property="VerticalAlignment" Value="Stretch"/>
        <Setter Property="RenderTransform">
            <Setter.Value>
                <ScaleTransform ScaleX="0"></ScaleTransform>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="Visibility" Value="Visible">
                <Trigger.EnterActions>
                    <BeginStoryboard Name="pendingProgressAni">
                        <Storyboard>
                            <DoubleAnimationUsingKeyFrames
                                Storyboard.TargetProperty="RenderTransform.ScaleX"
                                Duration="0:0:30" Timeline.DesiredFrameRate="1">
                                <DiscreteDoubleKeyFrame Value="0.1" KeyTime="0:0:3" />
                                <DiscreteDoubleKeyFrame Value="0.2" KeyTime="0:0:6" />
                                <DiscreteDoubleKeyFrame Value="0.3" KeyTime="0:0:9" />
                                <DiscreteDoubleKeyFrame Value="0.4" KeyTime="0:0:12" />
                                <DiscreteDoubleKeyFrame Value="0.5" KeyTime="0:0:15" />
                                <DiscreteDoubleKeyFrame Value="0.6" KeyTime="0:0:18" />
                                <DiscreteDoubleKeyFrame Value="0.7" KeyTime="0:0:21" />
                                <DiscreteDoubleKeyFrame Value="0.8" KeyTime="0:0:24" />
                                <DiscreteDoubleKeyFrame Value="0.9" KeyTime="0:0:27" />
                                <DiscreteDoubleKeyFrame Value="1.0" KeyTime="0:0:29.7" />
                            </DoubleAnimationUsingKeyFrames>
                        </Storyboard>
                    </BeginStoryboard>
                </Trigger.EnterActions>
                <Trigger.ExitActions>
                    <RemoveStoryboard BeginStoryboardName="pendingProgressAni"/>
                </Trigger.ExitActions>
            </Trigger>
        </Style.Triggers>
    </Style>

AddSorted to List/Collection

/// <summary>
/// Adds a new item with sorted by comparer in the collection.
/// </summary>
public static void AddSorted<T>(this IList<T> list, T item, IComparer<T> comparer = null)
{
    var comparerPara = comparer;

    if (comparerPara == null)
        comparerPara = Comparer<T>.Default;

    int i = 0;
    while (i < list.Count && comparerPara.Compare(list[i], item) < 0)
    {
        i++;
    }

    //you may want to invoke this on UI thread if context is at background.
    list.Insert(i, item);
}

Then any model which has IComparable<T> implemented will take effect in this extension method.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,362评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,330评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,247评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,560评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,580评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,569评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,929评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,587评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,840评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,596评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,678评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,366评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,945评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,929评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,165评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,271评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,403评论 2 342

推荐阅读更多精彩内容