在AttachedProperty中访问DataGrid.RowStyle

时间:2019-03-18 09:07:39

标签: c# wpf xaml attached-properties

XAML:

<DataGrid ItemsSource="{Binding Source={StaticResource Lines}}"                      
          uiwpf:DataGridExtensions.CanExportToExcel="True">
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="ContextMenu" Value="{StaticResource RowContextMenu}" />
        </Style>
    </DataGrid.RowStyle>
    ...
</DataGrid>

附加属性:

private static void CanExportToExcelChanged(
    DependencyObject d, 
    DependencyPropertyChangedEventArgs e)
{
    //Just my way of secure casting DependencyObject -> DataGrid
    if(d is DataGrid dataGrid)
    {
        Debug.Assert(dataGrid.RowStyle != null, "Why is this null?");
    }
}

问题:断言被触发-为什么?

1 个答案:

答案 0 :(得分:2)

这可能是在DataGrid上设置属性的顺序。

通常(我不知道有任何例外,但我不想在这里声明没有任何东西)属性是按照在XAML中定义的顺序设置的。因此,在设置DataGridExtensions.CanExportToExcel之前,您的True将被设置为DataGrid.RowStyle

您可以通过删除当前对uiwpf:DataGridExtensions.CanExportToExcel="True"的呼叫并放入:

<uiwpf:DataGridExtensions.CanExportToExcel>True</uiwpf:DataGridExtensions.CanExportToExcel>

之后,您设置了<DataGrid.RowStyle>

要使附加属性稳定,您可能需要使用CanExportToExcelChanged来设置RowStyle属性的绑定(并在CanExportToExcel设置为{{1时再次删除它}}。

相关问题