我无法获得使用转换器的自定义绑定,在构建项目时获取此信息:
错误2解析标记扩展时遇到类型'MS.Internal.Markup.MarkupExtensionParser + UnknownMarkupExtension'的未知属性'Converter'。
错误指向此代码:
<KeyBinding
Key="{helper:KeyboardShortcut InsertTargetToSource, Converter={StaticResource KeyGestureConverterKey},ConverterParameter=Key}"
Modifiers="{helper:KeyboardShortcut InsertTargetToSource, Converter={StaticResource KeyGestureConverterKey},ConverterParameter=Modifiers}"
Command="{Binding CopyToTargetCommand}"/>
KeyboardShortCut是来自设置文件的绑定:
public class KeyboardShortcutExtension : Binding
{
public KeyboardShortcutExtension()
{
Initialize();
}
public KeyboardShortcutExtension(string path)
: base(path)
{
Initialize();
}
private void Initialize()
{
this.Source = TI.Shortcuts.Default;
this.Mode = BindingMode.TwoWay;
}
}
转换器从字符串(如“Ctrl + Shift + X”)转换为Key和Modifiers:
private KeyGestureConverter mConverter = new KeyGestureConverter();
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var text = value.ToString();
var gesture = mConverter.ConvertFromInvariantString(text) as KeyGesture;
if (parameter == "Key")
{
return gesture.Key;
}
if (parameter == "Modifiers")
{
return gesture.Modifiers;
}
return gesture;
}
我有什么遗失的吗?或者,在尝试从设置文件中的字符串绑定到KeyBinding时,我应该采用不同的方法吗?
编辑:
使用以下代码,一切正常,但代码不可读。有没有办法自动生成这个,所以在我的标记中我会写例如只是
<MyKeyBinding Value="CopyToTargetCommand"/>
它会产生其余的吗?
<KeyBinding Command="{Binding CopyToTargetCommand}">
<KeyBinding.Key>
<helper:KeyboardShortcut Path="InsertTargetToSource" ConverterParameter="Key">
<helper:KeyboardShortcut.Converter>
<StaticResource ResourceKey="KeyGestureConverterKey"/>
</helper:KeyboardShortcut.Converter>
</helper:KeyboardShortcut>
</KeyBinding.Key>
<KeyBinding.Modifiers>
<helper:KeyboardShortcut Path="InsertTargetToSource" ConverterParameter="Modifiers">
<helper:KeyboardShortcut.Converter>
<StaticResource ResourceKey="KeyGestureConverterKey"/>
</helper:KeyboardShortcut.Converter>
</helper:KeyboardShortcut>
</KeyBinding.Modifiers>
</KeyBinding>
答案 0 :(得分:0)
class CustomizableKeyBinding : KeyBinding
{
public CustomizableKeyBinding()
: base()
{
}
StringToKeyGestureConverter converter = new StringToKeyGestureConverter();
public string Description
{
set
{
InitBindings(value);
}
}
private void InitBindings(string value)
{
BindingOperations.SetBinding(this, KeyBinding.KeyProperty, new KeyboardShortcutExtension(value) { Converter = converter, ConverterParameter = "Key" });
BindingOperations.SetBinding(this, KeyBinding.ModifiersProperty, new KeyboardShortcutExtension(value) { Converter = converter, ConverterParameter = "Modifiers" });
}
}
然后在XAML中:
<helper:CustomizableKeyBinding Command="{Binding CopyToTargetCommand}" Description="..."/>