TextBox Text set via a DataTrigger does not update the property value in the model

I am new to WPF and I want to clear the textBox value if the box is unchecked. I tried to do this using data triggers.

Below is the code:

<TextBox Text="{Binding Path=Amount,Mode=TwoWay}"> <TextBox.Style> <Style> <Style.Triggers> <DataTrigger Binding="{Binding Path=IsSelected}" Value="false"> <Setter Property="TextBox.Text" Value="{x:Null}"></Setter> </DataTrigger> </Style.Triggers> </Style> </TextBox.Style> </TextBox> 

My checkbox value is set in the "IsSelected" property in my model. Here, if the box is unchecked, then the updated value of the text, which {x: Null} in this case is not reflected in the "Sum" property of my model. Because of this, the text never changes in the user interface. The earlier set value of "Amount" is again set to the TextBox due to binding

Any help is appreciated. Let me know if you need more information or clarification Thank you.

+4
source share
1 answer

In such cases, I usually prefer the ViewModel / Model to do the β€œclear” part of the functionality,

therefore, in your case, I usually do something like:

 public bool IsSelected { get { return _isSelected; } private set { if (value == _isSelected) return; RaisePropertyChanging(() => IsSelected); _isSelected = value; RaisePropertyChanged(() => IsSelected); if (_isSelected == false) Amount = string.Empty } } 

Thus, the view is not responsible for any logic and therefore does not need a DataTrigger at all

Update:

The problem with your code is that when you install Text with a binding in a TextBox, it takes precedence over the value set in Style for the Text property. You can verify this using the following:

 <TextBox> <TextBox.Style> <Style TargetType="{x:Type TextBox}"> <Setter Property="Text" Value="{Binding Path=Amount, Mode=TwoWay}" /> <Style.Triggers> <DataTrigger Binding="{Binding Path=IsSelected}" Value="false"> <Setter Property="Text" Value="{x:Null}" /> </DataTrigger> </Style.Triggers> </Style> </TextBox.Style> </TextBox> 

Now the text will be cleared if CheckBox checked, however it will not update the binding ( Amount ), since essentially your binding is only active when you select CheckBox .

+6
source

Source: https://habr.com/ru/post/1479346/


All Articles