Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Binding with RelativeSource and AncestorType

Tags:

c#

wpf

xaml

I have a WPF application. It has a grid that is split into 4 rows. In the 2 row I have a datagrid that has its datacontext set to an object of OrderBlock. This all works fine. However I would like one of the column header text value of the datagrid be bound to a property in my view model.

Below is an example of what I have tried unsuccessfully.

<DataGridTextColumn Header="{Binding RelativeSource={RelativeSource 
   AncestorType={x:Type Window}}, Path=ColumnHeadInfo}" 
   Binding="{Binding RejectReason}" IsReadOnly="True"/>
like image 875
mHelpMe Avatar asked Dec 20 '13 13:12

mHelpMe


2 Answers

Window does not have a property called ColumnHeadInfo, but I assume your ViewModel is your Window's DataContext, and this probably has this property?!

If so, please try this instead:

Path=DataContext.ColumnHeadInfo

EDIT:
Since this alone did not solve your problem: The reason could be that the DataGridColumn is not part of the visual tree and thus cannot find any parent elements because it does not have any. Therefore, the RelativeSource AncestorType binding does not yield any result. This should be indicated by a warning in your output window. Probably, this link may help you.

like image 190
gehho Avatar answered Nov 14 '22 22:11

gehho


instead of controls i use "marker interfaces" to find the right datacontext.

"marker interfaces" just empty interfaces:

 public interface IDataContextColumnHeadInfoMarker{}

the view wich i know has the right datacontext is marked with the interface

public partial class MyViewWiththeDatagrid : UserControl, IDataContextMarkerLadeSolldatenCommand  

and now i can use the interface with relativesource binding instead of controls or ancestorlevel, that makes thing easier for some cases :)

<DataGridTextColumn Header="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:IDataContextColumnHeadInfoMarker}}, Path=DataContext.ColumnHeadInfo}"   
like image 35
blindmeis Avatar answered Nov 14 '22 23:11

blindmeis