首页 > 解决方案 > MVVM WPF:从 ViewModel 按名称更改项目的属性

问题描述

假设我在 XAMl 页面中定义了 12 个矩形,如下所示:

<Rectangle x:Name="C" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="226" Margin="10,10,0,0" Stroke="Black" VerticalAlignment="Top" Width="69"/>
<Rectangle x:Name="D" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="226" Margin="78,10,0,0" Stroke="Black" VerticalAlignment="Top" Width="69"/>
<Rectangle x:Name="E" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="226" Margin="146,10,0,0" Stroke="Black" VerticalAlignment="Top" Width="69"/>
<Rectangle x:Name="F" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="226" Margin="214,10,0,0" Stroke="Black" VerticalAlignment="Top" Width="69"/>
<Rectangle x:Name="G" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="226" Margin="281,10,0,0" Stroke="Black" VerticalAlignment="Top" Width="69"/>
<Rectangle x:Name="A" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="226" Margin="347,10,0,0" Stroke="Black" VerticalAlignment="Top" Width="69"/>
<Rectangle x:Name="B" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="226" Margin="414,10,0,0" Stroke="Black" VerticalAlignment="Top" Width="69"/>
<Rectangle x:Name="CSh" Fill="Black" HorizontalAlignment="Left" Height="121" Margin="47,10,0,0" Stroke="Black" VerticalAlignment="Top" Width="63"/>
<Rectangle x:Name="DSh" Fill="Black" HorizontalAlignment="Left" Height="121" Margin="115,10,0,0" Stroke="Black" VerticalAlignment="Top" Width="62"/>
<Rectangle x:Name="FSh" Fill="Black" HorizontalAlignment="Left" Height="121" Margin="249,10,0,0" Stroke="Black" VerticalAlignment="Top" Width="63"/>
<Rectangle x:Name="GSh" Fill="Black" HorizontalAlignment="Left" Height="121" Margin="317,10,0,0" Stroke="Black" VerticalAlignment="Top" Width="63"/>
<Rectangle x:Name="ASh" Fill="Black" HorizontalAlignment="Left" Height="121" Margin="385,10,0,0" Stroke="Black" VerticalAlignment="Top" Width="63"/>

如何在不使用CodeBehind的情况下从ViewModel更改特定矩形的颜色?

示例:如果我在键盘上按下键“A”,则我的 xaml 页面中名为“A”的元素必须用绿色着色,如果我在键盘上按下“B”,我的 XAML 上名为“B”的元素必须被涂成绿色等等。

我已经对绑定的工作原理有了一些基本的了解,但是我找不到任何解决方案,谁能指出我正确的方向?

标签: c#wpfmvvm

解决方案


首先,您需要将其添加到您的 xaml 代码中

<Rectangle x:Name="C" Fill="{Binding Color}" HorizontalAlignment="Left" Height="226" Margin="10,10,0,0" Stroke="Black" VerticalAlignment="Top" Width="69"/>

接下来你需要创建 ViewModel

publuc MyViewModel() :INotifyPropertyChanged
{
        Brush _color;
        Brush Color{get{return _color;} set{_color = value; OnPropertyChanged("Color")}}

  public MyViewModel()
  {
      Color = Brushes.Green;
  }
}

最后添加您的窗口的 xaml.cs 类

DataContext = new DERDashboardUserControlViewModel();

您可以在矩形周围添加按钮并创建将绑定到视图模型中的方法的命令。这是如何将 WPF 按钮绑定到 ViewModel 中的命令的链接


推荐阅读