使用多重绑定和模板绑定。

14

我正在WPF中制作自定义控件。我仍在学习TemplateBinding的各个方面(在自定义控件中经常使用)。

我注意到的一件事是,似乎无法在MulitBinding中使用TemplateBinding。

当我尝试这样做时:

<ComboBox.ItemsSource>
    <MultiBinding Converter="{StaticResource MyMultiConverter}">
        <Binding ElementName="PART_AComboBox" Path="SelectedItem"/>
        <TemplateBinding Property="MyListOne"/>
        <TemplateBinding Property="MyListTwo"/>
    </MultiBinding>
</ComboBox.ItemsSource>

我收到了这个错误:

该值“System.Windows.TemplateBindingExpression”不属于“System.Windows.Data.BindingBase”类型,并且无法在此通用集合中使用。
参数名: value

我有什么遗漏吗?有方法可以使它正常工作吗?

这是我现在使用的解决方法,但它有点取巧:

<ListBox x:Name="ListOne" 
         ItemsSource="{TemplateBinding MyListOne}" 
         Visibility="Collapsed" />
<ListBox x:Name="ListTwo" 
         ItemsSource="{TemplateBinding MyListTwo}"
         Visibility="Collapsed" />

<ComboBox.ItemsSource>
    <MultiBinding Converter="{StaticResource DictionaryFilteredToKeysConverter}">
        <Binding ElementName="PART_TextTemplateAreasHost" Path="SelectedItem"/>
        <Binding ElementName="ListOne" Path="ItemsSource"/>
        <Binding ElementName="ListTwo" Path="ItemsSource"/>
    </MultiBinding>
</ComboBox.ItemsSource>

我将ListBoxes绑定到依赖属性,然后在我的多重绑定中对ListBoxes的ItemsSource进行元素绑定。

正如我上面所说,这感觉像一个hack,我想知道是否有一种正确的方法来使用TemplateBinding作为其中一个组件的MultiBinding。

1个回答

30

您可以使用:

<Binding Path="MyListOne" RelativeSource="{RelativeSource TemplatedParent}"/>

TemplateBinding其实只是上述方式的一个简写,它非常严格地限制了可以使用的位置和方式(例如直接在模板内部而没有层次路径等)。

在这些问题方面,XAML编译器仍然不太擅长提供良好的反馈(至少在4.0版本中如此,对于这一问题专门测试了4.5版本也未改善)。我刚刚遇到了这个XAML:

<ControlTemplate TargetType="...">
    <Path ...>
        <Path.RenderTransform>
            <RotateTransform Angle="{TemplateBinding Tag}"/>
        </Path.RenderTransform>
    </Path>
</ControlTemplate>

程序编译并成功执行,但未将Tag的值绑定到旋转角度。经过研究发现该属性已被绑定,但值为零。基于我的经验(多年来一直面对这个问题),我进行了更改:

<ControlTemplate TargetType="...">
    <Path ...>
        <Path.RenderTransform>
            <RotateTransform Angle="{Binding Tag, RelativeSource={RelativeSource TemplatedParent}}"/>
        </Path.RenderTransform>
    </Path>
</ControlTemplate>

并且它运行良好。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接