4

我们创建了一个自定义 ComboBox 控件,它有一个按钮来清除 ComboBox 的选择:

<Style TargetType="{x:Type local:ClearableComboBox}">
    <Setter Property="SelectedItem" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:ClearableComboBox}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                    <DockPanel>
                        <Button Name="btnClear" DockPanel.Dock="Right" ToolTip="Clear" Width="20">
                            <Image Source="pack://application:,,,/img/icons/silk/cross.png" Stretch="None" />
                        </Button>
                        <ComboBox Name="comboBox"
                                  ItemsSource="{TemplateBinding ItemsSource}"
                                  SelectedItem="{TemplateBinding SelectedItem}"
                                  DisplayMemberPath="{TemplateBinding DisplayMemberPath}" />
                    </DockPanel>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

ItemsSource 的绑定工作正常,但 SelectedItem 的绑定不能。在谷歌上搜索后,我在这里找到了问题的解决方案。具体来说,将 SelectedItem 绑定更改为

SelectedItem="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SelectedItem}"

使其按预期工作。

为什么 SelectedItem 上的原始 TemplateBinding 不起作用,而 ItemsSource 的 TemplateBinding 工作得很好?

4

1 回答 1

7

差异之一(我认为,这是您的主要问题)TemplateBinding是 always OneWay,而Binding选择是OneWayTwoWay 取决于 property(这里有更多细节。)

您可能会在此讨论中发现其他差异。

于 2011-11-11T18:06:03.987 回答