Search code examples
c#wpfxamlattached-properties

Attached property not working


I am using DevExpress control TreeListControl to display data. This control has columns, like datagrid. I want to show values in the center of the cell. For that I'm using CellTemplate:

<dxg:TreeListColumn HorizontalHeaderContentAlignment="Center" Header="January">
    <dxg:TreeListColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding RowData.Row.January}" TextAlignment="Center"/>
        </DataTemplate>
    </dxg:TreeListColumn.CellTemplate>
</dxg:TreeListColumn>

But I have a lot of columns, and the only difference is value to display. So I decided to use a style and pass value with attached property. Style:

<Style x:Key="TreeListColumnStyle" TargetType="{x:Type dxg:TreeListColumn}">
   <Setter Property="HorizontalHeaderContentAlignment" Value="Center"/>
   <Setter Property="CellTemplate">
       <Setter.Value>
           <DataTemplate>
               <TextBlock Text="{TemplateBinding ap:BenDatagridValueProperty.DataGridValue}" TextAlignment="Center"/>
           </DataTemplate>
       </Setter.Value>
   </Setter> 
</Style>

And here is my AttachedProperty:

public static class BenDatagridValueProperty
{
    public static readonly System.Windows.DependencyProperty DataGridValueProperty = System.Windows.DependencyProperty.RegisterAttached(
    "DataGridValue",
    typeof(string),
    typeof(BenDatagridValueProperty),
    new System.Windows.FrameworkPropertyMetadata("", System.Windows.FrameworkPropertyMetadataOptions.Inherits));

    public static string GetDataGridValue(System.Windows.DependencyObject obj)
    {
        return (string)obj.GetValue(DataGridValueProperty);
    }

    public static void SetDataGridValue(System.Windows.DependencyObject obj, string value)
    {
        obj.SetValue(DataGridValueProperty, value);
    }
}

Remade column now looks like:

  <dxg:TreeListColumn Header="January" Style="{StaticResource TreeListColumnStyle}" ap:BenDatagridValueProperty.DataGridValue="15">

15 is just a test value. And it does not sets value in datagrid columns to 15 (it does not call method SetDataGridValue(DependencyObject obj, string value). If I will write a default value in AttachedProperty, then I can see default value in cells. Not sure where is error.


Solution

  • Try modify TreeListColumnStyle:

    <Style x:Key="TreeListColumnStyle" TargetType="{x:Type dxg:TreeListColumn}">
       <Setter Property="HorizontalHeaderContentAlignment" Value="Center"/>
       <Setter Property="CellTemplate">
           <Setter.Value>
               <DataTemplate>
                   <TextBlock ap:BenDatagridValueProperty.DataGridValue="{TemplateBinding ap:BenDatagridValueProperty.DataGridValue}" Text="{Binding Path=(ap:BenDatagridValueProperty.DataGridValue), RelativeSource={RelativeSource Self}}" TextAlignment="Center"/>
               </DataTemplate>
           </Setter.Value>
       </Setter> 
    </Style>