我想要的是将Image源绑定到 MyViewModel 实例的 ImageData 属性。出于某种原因,我无法将MyWindow.DataContext设置为MyViewModel实例(这是一个leagacy代码,这样做会花费太多)。
代码段如下所示,会出现以下错误
System.Windows.Data错误:4:无法找到带引用的绑定源' ElementName = myButton'。 BindingExpression:路径=标签;的DataItem = NULL;目标元素是' Image' (名称='&#39);目标财产是来源' (键入' ImageSource')
// This is the view model class
class MyViewModel : INotifyPropertyChanged
{
public string Name {get ... ;set ... ; }
public string ImageData { ... }
}
// this is the window class
class MyWindow
{
private MyViewModel _ViewModel = new MyViewModel();
public MyViewModel ViewModel
{ get { return _ViewModel; } }
. . .
}
MyWindow.Xaml
<devComponent:ButtonDropDown x:Name="myButton"
Tooltip="{Binding RelativeSource={RelativeSource AncestorType={x:Type mf:MyWindow}}, Path=ViewModel.Name}"
Tag="{Binding RelativeSource={RelativeSource AncestorType={x:Type mf:MyWindow}}, Path=ViewModel.ImageData}"
...>
<devComponent:ButtonDropDown.Image>
<Image Source="{Binding Path=Tag, ElementName=myButton}" />
</devComponent:ButtonDropDown.Image>
</devComponent:ButtonDropDown>
我也尝试使用下面的代码,但它仍然无效,因为Image不属于可视树
无法找到与参考资源绑定的来源&#39; RelativeSource FindAncestor,AncestorType =&#39; xxxxx&#39;,AncestorLevel =&#39; 1&#39;&#39;
<Button.Image>
<Image Source="{Binding RelativeSource={RelativeSource AncestorType={x:Type mf:MyWindow}}, Path=MyViewModel.ImageData}" />
</Button.Image>