附属物不工作

时间:2017-11-17 07:54:47

标签: c# wpf xaml attached-properties

我正在使用DevExpress控件TreeListControl来显示数据。此控件具有列,如datagrid。我想在单元格的中心显示值。为此,我使用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>

但我有很多专栏,唯一的区别就是显示价值。所以我决定使用一个样式并使用附加属性传递值。式:

<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>

这是我的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专栏现在看起来像:

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

15只是一个测试值。并且它没有将datagrid列中的值设置为15(它不调用方法SetDataGridValue(DependencyObject obj,string value)。如果我将在AttachedProperty中写入默认值,那么我可以在单元格中看到默认值。 不确定错误在哪里。

1 个答案:

答案 0 :(得分:1)

尝试修改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>