Search code examples
c#wpfdata-bindingtextbox

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


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.


Solution

  • 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>