我是WPF的新手,如果取消选中复选框,我想清除textBox的值.我试过通过数据触发器做到这一点.
以下是代码:
<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>
Run Code Online (Sandbox Code Playgroud)
我的复选框的值在My Model的"IsSelected"属性中设置.这里,如果取消选中该复选框,则文本的更新值(在这种情况下为{x:Null})不会反映在我的模型的"金额"属性中.因此,文本似乎永远不会在UI上更改.由于绑定,"Amount"早期设置值在TextBox中再次设置
任何帮助表示赞赏.如果您需要更多信息或澄清,请告诉我们.
在这种情况下,我通常更喜欢ViewModel/Model做功能的"清晰"部分,
因此,在你的情况下,我通常会这样做:
public bool IsSelected {
get {
return _isSelected;
}
private set {
if (value == _isSelected)
return;
RaisePropertyChanging(() => IsSelected);
_isSelected = value;
RaisePropertyChanged(() => IsSelected);
if (_isSelected == false)
Amount = string.Empty
}
}
Run Code Online (Sandbox Code Playgroud)
这样的视图并不适用于任何逻辑的责任,因此并不需要DataTrigger
在所有
更新:
您的代码问题是当您Text
使用Binding 设置TextBox
它时,它优先于您在Style
Text属性中设置的值.您可以使用以下方法检查:
<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>
Run Code Online (Sandbox Code Playgroud)
现在,这将在CheckBox
选中时清除文本,但是它不会更新您的Binding(Amount
),因为基本上您的Binding仅在CheckBox
选中时才有效.
归档时间: |
|
查看次数: |
8179 次 |
最近记录: |