如何基于ComboBox ControlTemplate的TemplatedParent的ItemSource的属性设置属性?

问题描述

我的ComboBox一个DataTemplate。我指的是这个 Can I use a different Template for the selected item in a WPF ComboBox than for the items in the dropdown part?,因为我的要求与此类似:

<ComboBox x:Name="MyComboBox" ItemsSource="{Binding Items}"
                    Style="{StaticResource ComboBoxStyle}"
                    Template="{StaticResource ComboBoxControlTemplate}"
                    ItemTemplateSelector="{UI:ComboBoxTemplateSelector
                    SelectedItemTemplate={StaticResource ComboBoxSelectedItemDataTemplate},DropdownItemstemplate={StaticResource ComboBoxDataTemplate}}"/>

效果很好,但我又提出了一个要求:基于ComboBox设置ToggleButton的{​​{1}}的{​​{1}}。因此,我在设计器页面上右键单击此Background,选择

编辑模板->编辑副本

生成自动模板。在自动生成的模板中,我得到:

SelectedItem

所以我要在上面的代码中更改的是ComboBox。我希望<ControlTemplate x:Key="ComboBoxControlTemplate" targettype="{x:Type ComboBox}"> <ToggleButton> <Border x:Name="splitBorder" Background="{TemplateBinding Background}" ...> <Path x:Name="Arrow" .../> </Border> </ToggleButton> </ControlTemplate> 基于称为Background="{TemplateBinding Background}" ItemSource viewmodel属性,就像在Background中一样,

Selectedname

搜索了很多,但不确定应该怎么做。请帮忙。谢谢。

解决方法

设置Background的{​​{1}}属性与设置ComboBox的{​​{1}}类似:

Background

以上内容将TextBlock属性绑定到<ComboBox x:Name="MyComboBox" ... Background="{Binding SelectedItem.SelectedName,RelativeSource={RelativeSource Self},Converter={StaticResource StringToColorConverter}}"> 当前选定项的Background属性。