【问题标题】:Binding nested UserControls to properties exposed in the ViewModel将嵌套的 UserControls 绑定到 ViewModel 中公开的属性
【发布时间】:2011-02-09 00:34:17
【问题描述】:

我有一个用户控件,上面有图像。它的 Visibility 属性绑定到 ViewModel 上的属性(名为“On”)(引发 PropertyChanged 事件)。现在我想创建另一个 UserControl,其中包含一些这样的 UserControl。它将有自己的 ViewModel,它将公开另一组应该影响这些图像用户控件的属性。

我可以只使用 FindName 并显式获取他们的视图模型并设置 On 属性,但我想知道是否有办法通过绑定来处理这个问题,例如。

<local:MyImageView x:Name="MyImage1" On="{Binding Image1On}" />

Image1On 将是第二个 UserControl 的 ViewModel 上的另一个属性。

【问题讨论】:

    标签: wpf


    【解决方案1】:

    我通常处理此问题的方法是让您正在谈论的新视图模型包含具有“On”属性的原始视图模型的实例。 (是直接属性还是它们的集合取决于情况)然后,您无需处理 UI 元素,而是仅处理视图模型的属性。

    例如:“房间”视图模型包含“灯光”视图模型的集合。

    public class RoomViewModel
    {
       LightViewModel frontLights
       {
          //implementation
       }
       LightViewModel rearLights
       { 
         //implementation
       }
    
       // Create a ICommand Implementation around this
       public void ToggleFrontLights(bool turnLightsOn)
       {
          frontLights.On = turnLightsOn;
       }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      • 2012-12-18
      • 1970-01-01
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      相关资源
      最近更新 更多