簡體   English   中英

TemplateBinding不適用於擴展ComboBox的自定義控件中的SelectedItem

[英]TemplateBinding does not work for SelectedItem in custom control extending ComboBox

我們創建了一個自定義的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的綁定則不能。 在Google上搜索后,我在這里找到了解決問題的方法。 具體來說,將SelectedItem綁定更改為

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

使它按預期工作。

為什么原先的TemplateBinding不能在SelectedItem上工作,而TemplateBinding for ItemsSource卻可以正常工作?

區別之一(在我看來,這是您所遇到的主要問題)是TemplateBinding始終為OneWay ,而Binding 根據屬性選擇為OneWayTwoWay (更多詳細信息在這里 。)

您可能在此討論中發現其他差異。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM