Tessa
Tessa

Reputation: 51

Setting a collection DependencyProperty from XAML (WPF)

I created a user control (FilterPicker), that has a certain list as a property. This is a dependency property so that it can be set when I use the user control.

public static readonly DependencyProperty StrategiesProperty = DependencyProperty.Register(
        "Strategies",
        typeof(List<FilterType>),
        typeof(FilterPicker),
        new FrameworkPropertyMetadata
        {
            DefaultValue = new List<FilterType> { FilterType.Despike },
            PropertyChangedCallback = StrategiesChangedCallback,
            BindsTwoWayByDefault = false,
        });

I am then trying to define this list in the .xaml file where I use this control.

<Filtering:FilterPicker Grid.Row="1" Strategy="{Binding Strategy}">
            <Filtering:FilterPicker.Strategies>
                <Filtering1:FilterType>PassThrough</Filtering1:FilterType>
                <Filtering1:FilterType>MovingAverage</Filtering1:FilterType>
                <Filtering1:FilterType>Despike</Filtering1:FilterType>
            </Filtering:FilterPicker.Strategies>
        </Filtering:FilterPicker>

However, it doesn't work. StrategiesChangedCallBack never gets called. If I set it through a binding, it works fine - just not when I try to define it in the xaml. So this works:

<Filtering:FilterPicker Grid.Row="1" Strategy="{Binding Strategy}" Strategies="{Binding AllStrategies}">

But not the previous snippet. Any ideas on what I'm doing wrong?

Upvotes: 2

Views: 3293

Answers (1)

Tessa
Tessa

Reputation: 51

From the comments on my original question I was able to piece it together:

  • Indeed the problem was I was only listening to the property being changed, and not to objects in the collection.
  • As predicted I had problems with it operating on the same collection instance.

In the end I changed my DependencyProperty to use an IEnumerable, which I define as a StaticResource in the .xaml that uses the FilterPicker UserControl.

DependencyProperty:

public static readonly DependencyProperty StrategiesProperty = DependencyProperty.Register(
        "Strategies",
        typeof(IEnumerable<FilterType>),
        typeof(FilterPicker),
        new FrameworkPropertyMetadata
        {
            DefaultValue = ImmutableList<FilterType>.Empty, //Custom implementation of IEnumerable
            PropertyChangedCallback = StrategiesChangedCallback,
            BindsTwoWayByDefault = false,
        });

Using it:

<Grid.Resources>
            <x:Array x:Key="FilterTypes" Type="{x:Type Filtering1:FilterType}" >
                <Filtering1:FilterType>PassThrough</Filtering1:FilterType>
                <Filtering1:FilterType>MovingAverage</Filtering1:FilterType>
                <Filtering1:FilterType>Fir</Filtering1:FilterType>
            </x:Array>
        </Grid.Resources>

<Filtering:FilterPicker Grid.Row="1" Strategies="{StaticResource FilterTypes}" />

Upvotes: 2

Related Questions