我们创建了一个自定义的ComboBox控件,其中带有一个清除ComboBox选择内容的按钮:
ItemsSource的绑定正常,但SelectedItem的绑定不起作用。通过在Google上搜索,我在此处找到了解决方法。具体来说,将SelectedItem绑定更改为
为什么原始的SelectedItem的TemplateBinding无法工作,而ItemsSource的TemplateBinding却没问题呢?
<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}"
可以使其按预期工作。为什么原始的SelectedItem的TemplateBinding无法工作,而ItemsSource的TemplateBinding却没问题呢?