WPF using MVVM: DataBinding with RelativeSource

I have a control and inside this control I have a resource with tempalte data:

<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" 

I have vm installed in my ViewModel folder, I implement mvvm. I can't get my binding to work, and I'm not sure why not.

Can someone tell me if my relative binding is true if it can really see my ImagePath property in my MainViewModel class?

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

Thanks.

+7
source share
2 answers

The View model is not part of your Visual tree. therefore, ancestor type search will not work there. and if you find a root parent that has a datacontext, you can use its property to bind to it.

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

Hi, I managed to get it to work.

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

I changed my AncestorTypeto be'Window, which was completely attached to my MainViewModel, and then used a DataContext. in my Way to be able to see my property.

Hope this helps someone else!

+7
source

All Articles