【发布时间】:2020-11-23 17:11:04
【问题描述】:
我有一个基于 'mvvm' 的 wpf 应用程序,它带有一个像这样的组合框样式控件模板,
<Style x:Key="Itmstyle" TargetType="ComboBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ComboBoxItem">
<Button Content="{Binding Txt}" Command="{Binding DataContext.ClickCmd, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ComboBox}}}"
Background="Transparent" BorderBrush="Transparent">
<Button.InputBindings>
<KeyBinding Key="Enter" Command="{Binding DataContext.ClickCmd, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ComboBox}}}"/>
</Button.InputBindings>
</Button>
</ControlTemplate>
</Setter.Value>
</Setter>
样式是这样使用的,
<ComboBox ItemContainerStyle="{StaticResource Itmstyle}"
ItemsSource="{Binding Values}"
DisplayMemberPath="Name"
SelectedIndex="{Binding Indx}"
IsSynchronizedWithCurrentItem="True"/>
当我使用键盘箭头时,按钮(在样式中)不会突出显示,只出现项目周围的虚线焦点;当我按 Enter 键时,ClickCmd 没有执行..任何想法!请告诉我。非常感谢。
【问题讨论】:
-
您正在替换整个
ControlTemplate,因此您将失去内置的突出显示。只需在ComboBox.ItemTemplate内使用DataTemplate即可。 -
@GazTheDestroyer:感谢您的回复。我添加了数据模板。但是现在,如果我单击按钮,则 ViewModel 中的 SelectedIndex 不会更新,并且如果我单击组合框项(按钮外的小部分),则索引会更新,但不会执行 ClickCmd。
-
你想要发生什么?如果您只想单击以选择组合项,为什么需要一个按钮?
-
我试图在 ComboBox 下拉菜单中单击相同条目时选择(并执行 ClickCmd),但选择相同条目时不会再次触发 SelectionChanged。为了克服这个问题,我尝试将 Button 作为组合框中所有条目的模板。
标签: wpf mvvm controltemplate