[英]"A binding can only be set on a DependencyProperty of a DependencyObject" error when attempting to bind this ValueConverter
[英]Can't bind to DependencyProperty child of DependencyObject
我不知道如何绑定我的图像:
<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());
}
希望您能帮助我。 我尝试了不同的方法,但似乎没有任何效果。
您如何设置数据上下文? 我复制了您的代码,并添加了另一个属性-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。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.