首页 > 解决方案 > 视图模型 (WPF) 中的 UI 更新命令

问题描述

我正在制作一个基于 MVVM 模式的 WPF 应用程序,其中用户单击树的项目(由颜色名称组成的超链接,具有相应前景的名称文本)来更改整个窗口的背景。我正在通过中继命令执行此操作,但 UI 在我正在编写命令的视图模型中是不可接受的。

XAML 中具有颜色名称的树:

<TreeView Name="tree" ItemSource="{Binding colorList, Mode=TwoWay}" Background="Transparent">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemSource={Binding Children}>
             <TextBlock><Hyperlink Command={Binding ColorChangerCommand} Foreground={Binding Foreground} TextDecorations="None"><TextBlock Text={Binding Name}/></Hyperlink></TextBlock>
        </HierarchicalDataTemplate>
     </TreeView.ItemTemplate>
 <TreeView>

我的视图模型中的命令:

public RelayCommand ColorChangerCommand{ get; set;}

public TreeViewModel() //Constructor of the View Model
{
   ColorChangerCommand= new RelayCommand(ChangeColor);
}

public void ChangeColor(object sender)
{
  this.Background= (sender as TreeViewItem).Foreground;
}

该命令在简单的代码隐藏中运行良好,但现在不在视图模型中。请帮忙?

标签: c#wpfmvvmbindingcommand

解决方案


this.Background指的是Background视图模型的属性,前提是该ChangeColor方法属于视图模型类。要改变窗口的背景,您需要将其绑定到Background视图模型的属性并引发一个事件来告诉 UI 进行更新。这需要您的视图模型来实现INotifyPropertyChanged事件:

public class ViewModel : INotifyPropertyChanged
{
    public RelayCommand ColorChangerCommand { get; set; }

    public TreeViewModel() //Constructor of the View Model
    {
        ColorChangerCommand = new RelayCommand(ChangeColor);
    }

    public void ChangeColor(object sender)
    {
        this.Background = (sender as TreeViewItem).Foreground;
    }

    private Brush background= Brushes.White;
    public Brush Background
    {
        get { return background; }
        set { Background = value; NotifyPropertyChanged(Background); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

XAML:

<Window .... Background="{Binding Background}" />

您还需要将DataContext窗口设置为您的视图模型类的实例并绑定如下Command属性Hyperlink

<Hyperlink Command="{Binding DataContext.ColorChangerCommand, RelativeSource={RelativeSource AncestorType=Window}}" 
           Foreground="{Binding Foreground}" TextDecorations="None">

推荐阅读