Wpf 使用mvvm在组合框中再次选择相同条目时执行命令
我的wpf“mvvm”应用程序中有组合框。 “我的组合框”中的项目有:“a”、“b”、“c”、“浏览文件夹”、“d” 以下是我试图做的:Wpf 使用mvvm在组合框中再次选择相同条目时执行命令,wpf,mvvm,combobox,Wpf,Mvvm,Combobox,我的wpf“mvvm”应用程序中有组合框。 “我的组合框”中的项目有:“a”、“b”、“c”、“浏览文件夹”、“d” 以下是我试图做的: (键盘)当我在最后一个浏览文件夹条目上按Enter键时,我必须执行命令(Cmd1)以打开文件浏览器 (键盘)-关闭和重新打开组合框并点击浏览器文件夹上的Enter键,应重新执行命令(Cmd1) 我尝试的是: 如果我将数据模板作为按钮写入组合框项目,则按钮命令仅适用于鼠标单击,而不适用于键盘输入键 <ComboBox.ItemTemplate>
<ComboBox.ItemTemplate>
<DataTemplate>
<Button Command="{Binding DataContext.Cmd1, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ComboBox}}}" Background="Transparent" Content="{Binding Name}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
如果我在mvvm的ComboBox中多次选择相同的条目,我如何执行命令!非常感谢您可以使用一个附加的行为来处理特定项目的
KeyDown
事件:
public class KeyDownBehavior
{
public static readonly DependencyProperty EnterCommandProperty = DependencyProperty.RegisterAttached(
"EnterCommand",
typeof(ICommand),
typeof(KeyDownBehavior),
new FrameworkPropertyMetadata(null, new PropertyChangedCallback(OnSet)));
public static void SetEnterCommand(UIElement element, ICommand value) =>
element.SetValue(EnterCommandProperty, value);
public static ICommand GetEnterCommand(UIElement element) =>
(ICommand)element.GetValue(EnterCommandProperty);
private static void OnSet(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
UIElement element = (UIElement)d;
element.KeyDown += OnKeyDown;
}
private static void OnKeyDown(object sender, KeyEventArgs e)
{
ICommand command = GetEnterCommand((UIElement)sender);
if (command != null)
command.Execute(null);
}
}
示例XAML标记:
<ComboBox>
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Style.Triggers>
<DataTrigger Binding="{Binding}" Value="Browse Folder">
<Setter Property="local:KeyDownBehavior.EnterCommand"
Value="{Binding DataContext.Cmd1,
RelativeSource={RelativeSource AncestorType={x:Type ComboBox}}}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.ItemContainerStyle>
<s:String>a</s:String>
<s:String>b</s:String>
<s:String>c</s:String>
<s:String>Browse Folder</s:String>
<s:String>d</s:String>
</ComboBox>
A.
B
C
浏览文件夹
D
感谢@mm8的快速回复。KeyDown没有启动,所以我使用了PreviewKeyDown,它以我想象的方式完美工作。使用此PreviewKeyDown处理程序,我的绑定SelectedIndex变量没有得到更新,而是手动更新。