无法绑定到DependencyObject的DependencyProperty子级

时间:2013-04-17 00:32:57

标签: c# wpf binding

我无法弄清楚如何绑定我的图像:

<Image Source="{ Binding  Path=ViewModel.MainViewModel.ProcessedImage }" Name="image1"/>

到DependencyProperty ProcessedImage ,它是从DependencyObject派生的自定义类的子元素:

class ViewModel : DependencyObject
{
    public static ViewModel MainViewModel { get; set; }

    [...]

    public BitmapImage ProcessedImage
    {
        get { return (BitmapImage)this.GetValue(ProcessedImageProperty); }
        set { this.SetValue(ProcessedImageProperty, value); }
    }
    public static readonly DependencyProperty ProcessedImageProperty = DependencyProperty.Register(
      "ProcessedImage", typeof(BitmapImage), typeof(ViewModel), new PropertyMetadata());
}

我希望你能帮我解决这个问题。我尝试过不同的方法,但似乎没什么用。

1 个答案:

答案 0 :(得分:1)

您是如何设置数据上下文的?我复制了你的代码并添加了另一个属性 - ProcessedImageName,其默认值为“Hello World”

public static readonly DependencyProperty ProcessedImageNameProperty = DependencyProperty.Register(
        "ProcessedImageName", typeof(string), typeof(ViewModel), new PropertyMetadata("Hello World"));

    public string ProcessedImageName {
get { return (string)this.GetValue(ProcessedImageNameProperty); }
set { this.SetValue(ProcessedImageNameProperty, value); }}

我按如下方式设置数据上下文:

    public MainWindow()
    {
        InitializeComponent();
        ViewModel.MainViewModel = new ViewModel();
        DataContext = ViewModel.MainViewModel;
    }

我将绑定路径设置为:

<TextBlock Text="{Binding Path=ProcessedImageName }"/>

就个人而言,我不会继续使用静态MainViewModel属性,而只是新建一个ViewModel实例

    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel();
    }

属性的路径是相对于数据上下文的,所以如果属性是Class.PropertyName而数据上下文是Class,那么绑定路径就是PropertyName。

相关问题