不能绑定到DependencyObject的子组件DependencyProperty

本文关键字:组件 DependencyProperty DependencyObject 绑定 不能 | 更新日期: 2023-09-27 18:09:47

我不知道如何绑定我的图像:

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

到DependencyProperty proces沉淀物,这是我的自定义类派生自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());
}
我希望你能帮我解决这个问题。我试过不同的方法,但似乎都不起作用。

不能绑定到DependencyObject的子组件DependencyProperty

如何设置数据上下文?我复制了您的代码并添加了另一个属性- 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); }}

I设置数据上下文如下:

    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。