10

I have a control and within that control I have a resource with a data tempalte:

  <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 set to my ViewModel folder, I am implementing mvvm. I cannot get my binding to work and I am unsure why not.

Can some tell me if my relative binding is correct, if it can actually see my property 'ImagePath' in my MainViewModel class?

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

Thank you.

user101010101
  • 1,609
  • 6
  • 31
  • 52
  • 1
    I advise using [Snoop](http://snoopwpf.codeplex.com/) and [enabling WPF trace information](http://msdn.microsoft.com/en-us/library/dd409960.aspx). They both show you what bindings are failing. I am also learning WPF alongside MVVM and am finding these two sources of information absolutely invaluable. – Adam Houldsworth May 30 '12 at 10:30

2 Answers2

15

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 all ready bound to my MainViewModel and then used 'DataContext.' in my Path to be able to see my property.

Hope this helps someone else!!

user101010101
  • 1,609
  • 6
  • 31
  • 52
  • Very useful even years later... works nicely for navigation system command on a container View, without using overengineered solutions or toolkits. – ZexDC Oct 06 '17 at 06:42
  • Thanks, in my case AncestorType is `UserControl` but the big thing I missed, was needint to reference the property via `DataContext` – PandaWood Sep 14 '21 at 02:10
6

you View model is not part of your Visual tree. so the find ancestor type will not work there. and if you find the root parent which is having the datacontext then you can use its property to bind with like.

<Image Source={...... Path=DataContext.MyProperty}"/>
JSJ
  • 5,653
  • 3
  • 25
  • 32