【发布时间】:2016-07-20 19:34:40
【问题描述】:
我正在尝试学习 WPF/MVVM,出于教育原因,我创建了一个简单的应用程序。我在尝试实现 Command Object 时遇到了一些问题。
单击按钮控件时,我希望使用Command Object 将网格的背景颜色更改为黄色。关于如何做到这一点有很多东西,但我想用干净的方式来做。一般来说,我想在View、ViewModel 和Command Object 之间实现松散耦合,以便测试这些类。
我也不想使用像 Prism 这样的库,因为我需要先完全理解 MVVM。
我有一个代码示例,但它当然没有功能。只是为了方便起见。
我对 XAML 的看法
<Window x:Class="Calendar.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Calendar"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="480">
<Grid Background="{Binding BackgroundColour}" Margin="0,0,2,0">
<Button Margin="197,247,200,-239" Grid.Row="3" Grid.ColumnSpan="2" Command="{Binding SubmitCommand}">Color</Button>
</Grid>
我的模型视图类
public class MainWindowViewModel : INotifyPropertyChanged {
//Command part
ICommand SubmitCommand;
public MainWindowViewModel(ICommand command) {
SubmitCommand = command;
}
//Data Binding part
public event PropertyChangedEventHandler PropertyChanged;
private Brush backgroundColour = (Brush)new BrushConverter().ConvertFromString("Red");
public Brush BackgroundColour {
get { return this.backgroundColour; }
set {
if (value != this.backgroundColour) {
this.backgroundColour = value;
var handler = this.PropertyChanged;
if (handler != null) {
handler(this, new PropertyChangedEventArgs("BackgroundColour"));
}
}
}
(它也有数据绑定部分,但与我的问题无关)
【问题讨论】: