Yaz*_*lul 3 c# wpf binding templatebinding
我们创建了一个自定义 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>
Run Code Online (Sandbox Code Playgroud)
ItemsSource 的绑定工作正常,但是 SelectedItem 的绑定没有。在谷歌搜索后,我在这里找到了问题的解决方案。具体来说,将 SelectedItem 绑定更改为
SelectedItem="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SelectedItem}"
使其按预期工作。
为什么 SelectedItem 上的原始 TemplateBinding 不起作用,而 ItemsSource 的 TemplateBinding 工作得很好?
区别之一(我认为这是您的情况的主要问题)TemplateBinding是 always OneWay,而Binding选择是OneWay或TwoWay 取决于 property。(更多细节在这里。)
您可能会在本次讨论中发现其他差异。
| 归档时间: |
|
| 查看次数: |
1943 次 |
| 最近记录: |