I am new to WPF and I want to clear a textBox's value if a check box is unchecked. I tried doing that through 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's value is set in "IsSelected" property of My Model. Here, if the checkbox is unchecked, then the text's updated value, which is {x:Null} in this case, is not reflecting in "Amount" property of my Model. Because of this the text never seems to be changed on the UI. The "Amount" earlier set value is getting set again in the TextBox because of binding
Any help is appreciated. Let me know in case you need any more information or clarification Thanks.
In such cases I normally prefer ViewModel / Model doing the "clear" part of the functionality,
hence in your case I'd normally 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
}
}
That way the View does not hold responsibility for any logic and thus doesn't need the DataTrigger
at all
Update:
The Problem with your code is when you set the Text
with a Binding in the TextBox
it takes precedence over the value you set in the Style
for the Text property. You can check this by using this:
<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>
This will now clear the Text when the CheckBox
is checked, however it will not be updating your Binding(Amount
) since essentially your Binding is only active when the CheckBox
is selected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With