'Binding custom properties in style
I have a custom Template for the DataGridColumnHeader.
My code (data grid):
<DataGrid x:Name="ReportDG"
ItemsSource="{Binding ElementName=Root, Path=SourceData, Mode=TwoWay}"
Style="{StaticResource ReportGridStyle}"
Height="500"
AutoGenerateColumns="False"
CanUserResizeRows="False"
HeadersVisibility="Column"
Sorting="ReportDG_Sorting">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding FIO, Mode=OneWay}" HeaderStringFormat="FIO"/>
...
My code (style):
<!-- DataGridColumnHeader style -->
<Style TargetType="DataGridColumnHeader" x:Key="ReportColumnHeaderStyle" >
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="Foreground" Value="Gray"/>
<Setter Property="FontSize" Value="18" />
<Setter Property="Padding" Value="3"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridColumnHeader}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Border x:Name="BackgroundBorder"
BorderThickness="0, 0, 0, 2"
Background="White"
BorderBrush="LightGray"
Grid.RowSpan="2"
Grid.ColumnSpan="2"/>
<controls:TextBoxWithPlaceholder
Grid.Row="0"
Grid.ColumnSpan="2"
Style="{StaticResource FilterTextBoxStyle}"
Placeholder="Filter by name"
HorizontalAlignment="Stretch"
Margin="4 2 4 2"/>
<ContentPresenter Margin="6, 0, 12, 0"
VerticalAlignment="Center"
Grid.Row="1"
Grid.Column="0"/>
<Path x:Name="SortArrow"
Visibility="Collapsed"
Data="M11.29,11.46a1,1,0,0,0,1.42,0l3-3A1,1,0,1,0,14.29,7L12,9.34,9.71,7A1,1,0,1,0,8.29,8.46Zm3,1.08L12,14.84l-2.29-2.3A1,1,0,0,0,8.29,14l3,3a1,1,0,0,0,1.42,0l3-3a1,1,0,0,0-1.42-1.42Z"
Stretch="Fill"
Grid.Column="1"
Grid.Row="1"
Width="12"
Height="14"
Fill="LightGray"
Margin="0,0,8,0"
VerticalAlignment="Center"
RenderTransformOrigin="0.5, 0.5"/>
...
I need to set binding between "Filter by name" textbox and some ViewModel field.
Also it would be good to set placeholder (for example "Filter by name") as DataGridTextColumn Property.
How I can do it?
Solution 1:[1]
You can bind the TextBox to a property of a parent element in the visual tree using the RelativeSource property of the binding:
<controls:TextBoxWithPlaceholder ...
Text="{Binding DataContext.ViewModelProperty, RelativeSource={RelativeSource AncestorType=DataGrid}}" />
Also it would be good to set placeholder (for example "Filter by name") as DataGridTextColumn Property. How I can do it?
You can bind to a property of the parent column using the Column property of the DataGridColumnHeader. The question is what property of the column to bind to. You may want to define a custom attached property.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mm8 |

