WPF:自定义依赖项属性上的relativesource数据绑定

时间:2014-12-10 16:53:07

标签: wpf data-binding relative customproperty

我正在尝试创建自定义多值组合框。所以基本上是一个带有一些复选框作为项目的组合框。我的想法是,保持整个控件完全可绑定,以便我可以随时重复使用。

这是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>

自定义属性背后的代码&#34; SelectedItems&#34;

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

现在,当我测试项目时,RelativeSource正确地解析为控件本身,但是路径上的绑定&#34; SelectedItems&#34;调试器声明失败,在RelativeSource对象上没有这样的Path。

我是否搞砸了绑定还是我做出了完整的逻辑错误?

1 个答案:

答案 0 :(得分:1)

您正在将RelativeSource设置为Source,而是设置RelativeSource属性,如下所示:

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