2016-02-23 125 views
0

我想使用按钮的内容将快捷键绑定到按钮以查找适当的快捷方式。WPF:根据按钮内容绑定到按钮的快捷键

我在字符串和关联的快捷键的代码隐藏字典。通过明确地引用字典和密钥来取出密钥是没有问题的。

在下面的示例:

<Button Content="Picture" 
     Command="{Binding TestCmd}"> 
    <Button.InputBindings> 
     <KeyBinding Key="{Binding Shortcuts[Picture]}" 
        Command="{Binding Command, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}"/> 
    </Button.InputBindings> 
</Button> 

我想要做的使用按钮的内容,作为查找的快捷键是什么。实质上Key="{Binding Shortcuts[BUTTON.CONTENT]}"但是正确的XAML。

回答

0

我不认为这可以用XAML方式完成。一个可能的解决方案是为此编写一个转换器。

XAML:

<Button Content="Picture" Command="{Binding TestCmd}"> 
    <Button.InputBindings> 
     <KeyBinding Command="{Binding Command, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}"> 
      <KeyBinding.Key> 
       <MultiBinding Converter="{StaticResource DictionaryMultiValueConverter}"> 
        <Binding Path="Shortcuts" /> 
        <Binding Path="Content" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=Button}" /> 
       </MultiBinding> 
      </KeyBinding.Key> 
     </KeyBinding> 
    </Button.InputBindings> 
</Button> 

和转换器:

public class DictionaryMultiValueConverter : IMultiValueConverter 
{ 
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) 
    { 
     if(values.Length != 2) 
      throw new ArgumentException(@"DictionaryMultiValueConverter needs exactly two values", "values"); 

     var dict = values[0] as IDictionary; 
     var key = values[1]; 

     return dict != null && key != null && dict.Contains(key) 
      ? dict[key] 
      : DependencyProperty.UnsetValue; 
    } 

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

转换得到你Dictionary作为其第一个值,并选择作为其第二值的关键。然后它返回值为Dictionary中传递的值。

+0

谢谢。我在整个方法中发现的一个问题是,按钮必须专注于听按键。所以我要去一个完全不同的方向,并利用已经工作的定制按键。但再次感谢! –