Dot-Net

將 MultiBinding 與 TemplateBindings 一起使用

  • June 14, 2019

我正在 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”類型,不能在此通用集合中使用。

參數名稱:值

我錯過了什麼嗎?有沒有辦法使這項工作?

這是我要解決的方法,但它有點像黑客:

<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 綁定到依賴屬性,然後在我的 mulitbinding 中將元素綁定到列錶框的 ItemsSource。

正如我上面所說,這感覺像是一種 hack,我想知道是否有正確的方法來使用 TemplateBinding 作為組件之一進行 MultiBinding。

你可以使用:

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

它工作得很好。

引用自:https://stackoverflow.com/questions/14342644