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"/>
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.
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}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With