gpt4 book ai didi

wpf - 通过DataTrigger设置的TextBox的Text不更新Model中的属性值

转载 作者:行者123 更新时间:2023-12-04 20:39:58 24 4
gpt4 key购买 nike

我是 WPF 新手,如果未选中复选框,我想清除文本框的值。我尝试通过数据触发器来做到这一点。

下面是代码:

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

我的复选框的值在我的模型的“IsSelected”属性中设置。在这里,如果未选中复选框,则文本的更新值(在这种情况下为 {x:Null})不会反射(reflect)在我的模型的“金额”属性中。因此,UI 上的文本似乎永远不会更改。由于绑定(bind),“金额”较早的设置值在 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
}
}

这样 View 不对任何逻辑负责,因此不需要 DataTrigger根本

更新:

您的代码的问题是当您设置 TextTextBox 中的绑定(bind)它优先于您在 Style 中设置的值对于文本属性。您可以使用以下方法进行检查:
<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>

这将在 CheckBox 时清除文本。已检查,但是它不会更新您的 Binding( Amount ),因为本质上您的 Binding 仅在 CheckBox 时才处于事件状态被选中。

关于wpf - 通过DataTrigger设置的TextBox的Text不更新Model中的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16397570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com