【问题标题】:How to Use DataTrigger to set a property defined in the ViewModel in WPF如何使用 DataTrigger 设置 WPF 中 ViewModel 中定义的属性
【发布时间】:2011-06-15 19:43:57
【问题描述】:

我正在编写一个 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?

【问题讨论】:

    标签: wpf datatrigger


    【解决方案1】:

    DataTriggers 中的设置器应仅更改 UI 元素的属性(而且它们仅适用于 DependencyProperties)。
    直接设置StatusBarItem的Foregound属性,设置Style的TargetType。那应该有帮助。

       <Style TargetType="{x:Type StatusBarItem}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding HasError}" Value="True">
                    <Setter Property="Foreground" Value="Red" />
                </DataTrigger>
                <DataTrigger Binding="{Binding HasError}" Value="False">
                    <Setter Property="Foreground" Value="Black" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    

    在 ViewModel 中包含有关视觉表示的信息通常不是一个好主意。

    【讨论】:

      猜你喜欢
      • 2011-01-09
      • 1970-01-01
      • 2013-06-25
      • 2011-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多