如何使用 DataTrigger 设置 WPF 中 ViewModel 中定义的属性
我正在编写一个 XAML 文件,它使用 DataTrigger 在 ViewModel 中设置属性。 ViewModel类定义为:
public class ShellModel : INotifyPropertyChanged
{
public Brush ForegroundBrush
{
get; set;
}
....................
}
我想在View.xaml中使用DataTrigger来设置属性ForegroundBrush。我写的XAML是:
<StatusBar Name="statusBar" Grid.Row="3">
<StatusBarItem>
<StatusBarItem.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding HasError}" Value="True">
<Setter Property="ForegroundBrush" Value="Red" />
</DataTrigger>
<DataTrigger Binding="{Binding HasError}" Value="False">
<Setter Property="ForegroundBrush" Value="Black" />
</DataTrigger>
</Style.Triggers>
</Style>
</StatusBarItem.Style>
<TextBlock Name="statusBarMessage" Foreground="{Binding ForegroundBrush}" Text="{Binding StatusMessage}"></TextBlock>
</StatusBarItem>
........................
这不能编译。当我更改为时,
<Setter Property="ForegroundBrush" Value="Black" />
它
<Setter Property="ShellModel.ForegroundBrush" Value="Black" />
给了我错误:
依赖属性字段缺失....
我该如何编写这个以便DataTrigger可以在ViewModel中设置属性ForegroundBrush?
I am writing a XAML file which use DataTrigger to set a property in the ViewModel. The ViewModel class defined as:
public class ShellModel : INotifyPropertyChanged
{
public Brush ForegroundBrush
{
get; set;
}
....................
}
I want to use DataTrigger in the View.xaml to set the property ForegroundBrush. The XAML I wrote is:
<StatusBar Name="statusBar" Grid.Row="3">
<StatusBarItem>
<StatusBarItem.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding HasError}" Value="True">
<Setter Property="ForegroundBrush" Value="Red" />
</DataTrigger>
<DataTrigger Binding="{Binding HasError}" Value="False">
<Setter Property="ForegroundBrush" Value="Black" />
</DataTrigger>
</Style.Triggers>
</Style>
</StatusBarItem.Style>
<TextBlock Name="statusBarMessage" Foreground="{Binding ForegroundBrush}" Text="{Binding StatusMessage}"></TextBlock>
</StatusBarItem>
........................
This does not compile. When I changed the
<Setter Property="ForegroundBrush" Value="Black" />
to
<Setter Property="ShellModel.ForegroundBrush" Value="Black" />
it gives me error:
Dependency property field missing ....
How shall I write this so that the DataTrigger can set the property ForegroundBrush in the ViewModel?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
DataTriggers 中的 Setter 应该仅更改 UI 元素的属性(并且它们仅适用于 DependencyProperties)。
直接设置 StatusBarItem 的 Foreground 属性并设置 Style 的 TargetType。那应该有帮助。
无论如何,在 ViewModel 中获取有关视觉表示的信息通常都不是一个好主意。
Setters in your DataTriggers should change properties of your UI elements only (and also they only work with DependencyProperties).
Set the
Foregound
Property of your StatusBarItem directly and set the TargetType of the Style. That should help.Having information about the visual representation in your ViewModel is usually not a good idea anyway.