wpfxamldata-bindingrelativesourcecustomproperty

WPF: relativesource data binding on a custom dependencyproperty


I'm trying to create a custom multi value combobox. So basically a combobox with some checkboxes as items. The idea is, to keep the whole control fully bindable, so that I can be reused any time.

Here's the XAML

<ComboBox x:Class="WpfExtensions.Controls.MultiSelectComboBox"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
          xmlns:local="clr-namespace:WpfExtensions.Controls"
             mc:Ignorable="d" d:DesignHeight="23" d:DesignWidth="150">
    <ComboBox.Resources>
        <local:CheckBoxConverter x:Key="CheckBoxConverter" />
    </ComboBox.Resources>
    <ComboBox.ItemTemplateSelector>
        <local:MultiSelectBoxTemplateSelector>
            <local:MultiSelectBoxTemplateSelector.SelectedItemsTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Source={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:MultiSelectComboBox}}, Path=SelectedItems, Converter={StaticResource CheckBoxConverter}}" />
                </DataTemplate>
            </local:MultiSelectBoxTemplateSelector.SelectedItemsTemplate>
            <local:MultiSelectBoxTemplateSelector.MultiSelectItemTemplate>
                <DataTemplate>
                    <CheckBox Content="{Binding}" HorizontalAlignment="Stretch"
                      Checked="CheckBox_Checked" Unchecked="CheckBox_Checked" Indeterminate="CheckBox_Checked" Click="CheckBox_Checked" />
                </DataTemplate>
            </local:MultiSelectBoxTemplateSelector.MultiSelectItemTemplate>
        </local:MultiSelectBoxTemplateSelector>
    </ComboBox.ItemTemplateSelector>
</ComboBox>

And the code behind for the custom property "SelectedItems"

public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.Register("SelectedItems", typeof(IList), typeof(MultiSelectComboBox));

[Bindable(true)]
public IList SelectedItems
{
    get
    {
        return (IList)GetValue(SelectedItemsProperty);
    }
    private set
    {
        SetValue(SelectedItemsProperty, value);
    }
}

Now when I test the project, the RelativeSource is resolved correctly towards the control itself, however the Binding on the path "SelectedItems" fails with the debugger stating, that there is no such Path on the RelativeSource object.

Did I mess up the binding or did I make a complete logical error?


Solution

  • You are setting a RelativeSource as the Source, instead set the RelativeSource propperty like so:

    <TextBlock Text="{Binding Path=SelectedItems, RelativeSource={RelativeSource AncestorType={x:Type local:MultiSelectComboBox}}, Converter={StaticResource CheckBoxConverter}}" />