WPF 数据触发器和更改控件的样式
我正在使用自定义验证引擎来验证我的 ViewModel 属性。我被困在最后一步了。我想在验证失败时更改 TextBox
的背景颜色。因此,我实现了 DataTrigger 并将其绑定到 HasError 属性。 HasError 是一个普通的 CLR 属性。
public bool HasError
{
get
{
var hasError = Errors.Count() > 0;
return hasError;
}
}
代码如下:
<Style x:Key="textBoxStyle" TargetType="{x:Type TextBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=HasError}" Value="True">
<Setter Property="Background" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
问题是,当将 this.DataContext
分配给视图模型时,它只会被触发一次。所以,我想也许我可以使用依赖属性而不是普通属性,但这也没有成功。
有什么想法吗?
更新:
似乎 DataTrigger
仅在挂钩到 CLR 属性而不是依赖项属性时才会触发。
更新2:
如果只有以下代码有效:
****<Trigger Property="{Binding Path=HasError}" Value="True">
<Setter Property="Background" Value="Red" />
</Trigger>****
更新3有效:
正如答案提到的,我必须触发INotifyPropertyChanged
事件。
公开 可观察集合 错误 { 获取 { 返回 (ObservableCollection)GetValue(ErrorsProperty); } 放 { SetValue(ErrorsProperty, 值);
OnPropertyChanged("HasError"); } }
I am using my custom validation engine to validate my ViewModel properties. I am stuck at the last step. I want to change the background color of the TextBox
when the validation fails. So, I implemented DataTrigger
s and binded it to the HasError property. HasError is a normal CLR property.
public bool HasError
{
get
{
var hasError = Errors.Count() > 0;
return hasError;
}
}
And here is the code:
<Style x:Key="textBoxStyle" TargetType="{x:Type TextBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=HasError}" Value="True">
<Setter Property="Background" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
The problem is that it will be fired only once when the this.DataContext
is assigned to a view model. So, I thought maybe I can use Dependency Property instead of the normal property but that did not worked out either.
Any ideas?
UPDATE:
It seems like the DataTrigger
s are only fired when hooked to the CLR properties and not the dependency properties.
UPDATE 2:
If only the following code worked:
****<Trigger Property="{Binding Path=HasError}" Value="True">
<Setter Property="Background" Value="Red" />
</Trigger>****
UPDATE 3 WORKING:
As the answer mentioned I had to fire the INotifyPropertyChanged
event.
public
ObservableCollection
Errors
{
get { return (ObservableCollection)GetValue(ErrorsProperty);
}
set
{
SetValue(ErrorsProperty, value);OnPropertyChanged("HasError"); } }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
WPF 系统永远不会知道您的
HasError
属性已更改,这就是它只触发一次的原因。实现此目的的方法之一是实现INotifyPropertyChanged
并在错误集合发生更改时触发PropertyChanged
事件。WPF system will never know that your
HasError
property changed, that's why it only fires once. One of the methods to accomplish this is implementingINotifyPropertyChanged
and firingPropertyChanged
events when the collection of errors changes.