Felix D.
Felix D.

Reputation: 5123

Access DataGrid.RowStyle in AttachedProperty

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>

AttachedProperty:

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?");
    }
}

Problem: Assert is getting triggered - WHY ?

Upvotes: 2

Views: 72

Answers (1)

canton7
canton7

Reputation: 42320

This is probably the order in which the properties are being set on the DataGrid.

In general (I don't know of any exceptions, but I don't want to claim there aren't any) properties are set in the order that they're defined in XAML. So your DataGridExtensions.CanExportToExcel will be set to True before DataGrid.RowStyle is set.

You can test this by removing your current call to uiwpf:DataGridExtensions.CanExportToExcel="True", and putting:

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

After you set <DataGrid.RowStyle>.

To make your attached property robust, you will probably need to use CanExportToExcelChanged to set a binding on the RowStyle property (and remove it again when CanExportToExcel is set to False).

Upvotes: 2

Related Questions