Is it possible to update a databinding source value with the set TargetNullValue in case it is 'null'?

时间:2019-04-08 13:25:39

标签: c# wpf data-binding textbox

Just out of interest....

In case I have a ViewModel with an uninitialized string, which is bound to a Textbox, I can use TargetNullValue to display a default value. However, I was wondering if I can use the same value to update the string in case it is null?

Basically instead of

    set
    {
        if(value != null) text = value;
        else value = "defaultstring";
        OnPropertyChanged();
    }  

just do the same thing from the databinding using TargetNullValue.

1 个答案:

答案 0 :(得分:1)

You can manipulate the getter as well as the data binding will use the get():

    private string text;

    public string Text
    {
        get
        {
            if (text== null)
                return "default value";
            else
                return this.text;
        }
        set { this.text= value; }

    }

However, if you want to do it in Pure XAML you can use a DataTrigger for this:

<TextBlock Text="{Binding MyText}">
   <TextBlock.Style>
        <Style TargetType="{x:Type TextBlock }">
            <Style.Triggers>
                <DataTrigger Binding="{Binding MyText}" Value="{x:Null}">
                    <Setter Property="Text" Value="DefaultValue"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>