Chris
Chris

Reputation: 5514

DependencyProperty default value and subclassed DataGrid breaks properties

I've come across some strange behaviour while trying to subclass wpf's DataGrid control.

Let's say I have:

class CustomDataGrid<T> : DataGrid { ... }
class FooDataGrid : CustomDataGrid<Foo> { }

And some xaml:

<local:FooDataGrid ItemsSource="..." SelectionMode="Single" SelectionUnit="FullRow" />

Everything works fine, and I can only select one row at a time. If I however attempt to change the defaults for SelectionMode/SelectionUnit by doing this:

static CustomDataGrid()
{
    DataGrid.SelectionModeProperty.OverrideMetadata( typeof( CustomDataGrid<T> ), new FrameworkPropertyMetadata( DataGridSelectionMode.Single ) );
    DataGrid.SelectionUnitProperty.OverrideMetadata( typeof( CustomDataGrid<T> ), new FrameworkPropertyMetadata( DataGridSelectionUnit.FullRow ) );
}

And change the xaml to:

<local:FooDataGrid ItemsSource="..." />

It does not seem to care about my defaults, and I can select multiple rows. Now, the weird thing is that if I try to set the properties manually in xaml again (while still having the defaults in the static constructor), I can still select multiple rows. So somehow overriding the metadata screws with the workings of those dependency properties, causing wpf to not care about the values set in the xaml.

Does anyone have a clue what is going on here?

Upvotes: 2

Views: 468

Answers (1)

max
max

Reputation: 34427

Actual multiselect behavior is controlled by CanSelectMultipleItems property, which defaults to true and is only updated when SelectionMode property changes. Overriding default value won't call property changed handler, so CanSelectMultipleItems remains true. Now if you try to set values in XAML, dependency property system starts working against you: default value is DataGridSelectionMode.Single, and you are setting property to the same value, so property changed handler is not called again and nothing happens.

Simpliest solution - add a non-static constructor and initialize CanSelectMultipleItems property:

public CustomDataGrid()
{
    CanSelectMultipleItems = SelectionMode != DataGridSelectionMode.Single;
}

Also you could declare custom style for your datagrid and set property values in style - it seems like a more "WPF-way" to do such things.

Upvotes: 1

Related Questions