X

WPF DataTemplate bind property to Parent ViewModel

WPF

Here is a hint when using WPF and you may come into a situation where you want to databind an element to its Parent ViewModel.

As an example lets say you have a view that is binding to ViewModel and inside your xaml you have a control that has DataTemplate
The code Below we are using the BusyIndicator from https://wpftoolkit.codeplex.com/


            
                 
                          <TextBlock Text="{Binding MyProcessText}" FontWeight="Bold" HorizontalAlignment="Center"/>
            


Our ViewModel looks like

public class ViewModel
{
  private string _text;
  public string MyProcessText { 
   get {return _text; }
   set { _text = value; RaisePropertyChanged("MyProcessText"); }
}

We would assume that the property would bind, but actually it doesn’t since the datatemplate is there.

So what we need to do is bind it to its parent viewmodel

What we need to provide is RelativeSource and the AncestorType, below we are using UserControl but it could also be Window or a provided type like AncestorType={x:Type XYZObject}

<TextBlock Text="{Binding MyProcessText, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}" FontWeight="Bold" HorizontalAlignment="Center"/>
Categories: .NET C# WPF
Taswar Bhatti:
Related Post