我应该如何根据其 TemplatedParent 的 ItemSource 的 属性 设置 ComboBox ControlTemplate 的 属性?

How should I set a ComboBox ControlTemplate's property based on its TemplatedParent's ItemSource's property?

我的组合框有一个数据模板。我指的是这个 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}}"/>

效果很好,但我收到了另一个请求:根据 SelectedItem 设置 ComboBoxToggleButtonBackground。所以我在设计器页面右击这个ComboBox,选择

Edit Template -> Edit a Copy

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

<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}"。我希望 Background 基于一个名为 SelectedNameItemSource ViewModel 属性 就像在 DataTemplate 中一样 我有类似的东西:

<DataTemplate x:Key="ComboBoxSelectedItemDataTemplate">
    <Grid>
        ...
        <TextBlock Background="{Binding Converter="{StaticResource StringToColorConverter}", Path="SelectedName"}"/>
    </Grid>
</DataTemplate>

我搜索了很多但不确定我应该怎么做才能实现这一目标。请帮忙。谢谢。

设置 ComboBoxBackground 属性 类似于设置 TextBlockBackground:

<ComboBox x:Name="MyComboBox" ...
          Background="{Binding SelectedItem.SelectedName, 
            RelativeSource={RelativeSource Self}, Converter={StaticResource StringToColorConverter}}">

以上将Background属性绑定到ComboBox当前选中项的SelectedName属性。