c# - 视图模型 (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;
}
该命令在简单的代码隐藏中运行良好,但现在不在视图模型中。请帮忙?
解决方案
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">
推荐阅读
- arrays - MASM 数组长度
- wso2 - 尝试将新 API 部署到 WSO2 服务器
- javascript - 将事件侦听器添加到使用 Javascript 从 API 捕获的动态生成的元素
- ios - 如何在 SwiftUI 中选择多个项目
- node.js - NestJS 与 Docker 和 Portainer
- assembly - 单独输出进位标志。MASM 大会
- r - 在 R 中读取包含向量 (c(x,y)) 的 .csv
- javascript - React:如何呈现嵌套的 JSON 数据?
- c# - 如何在记录类型中添加默认值?- F#
- javascript - 如何将值从角度方法传递给属性