我有一个 TextBox,如果 TextBox 有 Text.Length >0
那么我必须更改 HasChar 属性 True
否则 False
。在这里我无法在 Setter 中绑定(bind)属性。
XAML 源代码:
<TextBox Text="WPF">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<DataTrigger Value="0"
Binding="{Binding Text.Length, RelativeSource={RelativeSource Self}}">
<Setter Property="{Binding HasChar}" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
View 模型 C# 源代码:
private bool _hasChar= true;
public bool HasChar
{
get { return _hasChar; }
set
{
_hasChar= value;
OnPropertyChanged();
}
}
最佳答案
你在滥用触发器。
正确的做法:
1) XAML:
<TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}"/>
2) 查看模型。您不需要将 setter 添加到 HasChar
。如果此属性绑定(bind)到 View 中的某些内容,只需引发适当的 PropertyChanged
:
public class ViewModel : INotifyPropertyChanged
{
// INPC implementation is omitted
public string Text
{
get { return text; }
set
{
if (text != value)
{
text = value;
OnPropertyChanged();
OnPropertyChanged("HasChar");
}
}
}
private string text;
public bool HasChar
{
get { return !string.IsNullOrEmpty(Text); }
}
}
关于c# - 如何根据条件将 VIew 模型的属性绑定(bind)到 DataTrigger Setter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34390477/