我想使用按钮的内容将快捷键绑定到按钮,以查找相应的快捷方式。
我在字符串和相关快捷键的代码隐藏中有一个字典。通过明确引用字典和键来提取密钥没有问题。
以下示例有效:
<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 :(得分: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
发送密钥的值。