【问题标题】:WPF using MVVM: DataBinding with RelativeSource使用 MVVM 的 WPF:使用 RelativeSource 进行数据绑定
【发布时间】:2012-06-04 13:44:36
【问题描述】:

我有一个控件,并且在该控件中我有一个带有数据模板的资源:

  <DataTemplate DataType="{x:Type local:FlowModel}">
    <Image Source="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type vm:MainViewModel}}, Path=MainViewModel.ImagePath}"/>
  </DataTemplate>

 xmlns:vm="clr-namespace:CortexMonitoringTool.ViewModel"

我已将 vm 设置为我的 ViewModel 文件夹,我正在实现 mvvm。我无法让我的绑定工作,我不确定为什么不。

有人能告诉我我的相对绑定是否正确,它是否真的可以在我的 MainViewModel 类中看到我的属性“ImagePath”?

public String ImagePath
    {
        get
        {
            return _imagePath;
        }
        set
        {
            if (_imagePath == value)
            {
                return;
            }
            _imagePath = value;
            RaisePropertyChanged("ImagePath");
        }
    }

谢谢。

【问题讨论】:

  • 我建议使用Snoopenabling WPF trace information。它们都向您展示了哪些绑定失败了。我还在与 MVVM 一起学习 WPF,我发现这两个信息来源绝对是无价的。

标签: c# wpf c#-4.0 mvvm mvvm-light


【解决方案1】:

嗨,我设法让它工作了。

  <DataTemplate DataType="{x:Type local:FlowModel}">
    <Image Source="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.ImagePath}"/>
  </DataTemplate>

我将我的 AncestorType 更改为“Window”,它已准备好绑定到我的 MainViewModel,然后使用“DataContext”。在我的路径中能够看到我的财产。

希望这对其他人有所帮助!

【讨论】:

  • 即使在多年后也非常有用...非常适合容器视图上的导航系统命令,无需使用过度设计的解决方案或工具包。
  • 谢谢,在我的例子中,AncestorType 是 UserControl,但我错过了一件大事,需要通过 DataContext 引用该属性
【解决方案2】:

您的视图模型不是您的可视树的一部分。所以 find 祖先类型在那里不起作用。如果您找到具有 datacontext 的根父级,那么您可以使用它的属性与 like 绑定。

<Image Source={...... Path=DataContext.MyProperty}"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-21
    • 2017-08-05
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 2011-06-16
    相关资源
    最近更新 更多