考虑一些派生类型的标准附属物:
public class DerivedKeyBinding : KeyBinding
{
public string Name; //shortened, make this propdp
}
public class KeyBindingExtenstions
{
public static DerivedKeyBinding GetCommand(DependencyObject obj) {
return (DerivedKeyBinding)obj.GetValue(CommandProperty);
}
public static void SetCommand(DependencyObject obj, DerivedKeyBinding value) {
obj.SetValue(CommandProperty, value);
}
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached("Command", typeof(DerivedKeyBinding), typeof(KeyBindingExtenstions), new UIPropertyMetadata(null, CommandChanged));
private static void CommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var commandValue = GetCommand(d);
}
}
稍后在XAML中设置:
<Grid>
<Grid.Style>
<Style>
<Setter Property="local:KeyBindingExtenstions.Command">
<Setter.Value>
<local:DerivedKeyBinding Name="{Binding Title, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}"/>
</Setter.Value>
</Setter>
</Style>
</Grid.Style>
</Grid>
然而,这将在网络上崩溃
var commandValue = GetCommand(d);
由于
local:DerivedKeyBinding
KeyBinding
在某个过程中。
出于某种奇怪的原因
DerivedKeyBinding
正在使用类型的值设置类型
键绑定
(尽管价值
明确地
开始
派生键绑定
在XAML中)。
系统InvalidCastException:“无法强制转换”系统类型的对象。窗户。输入键绑定“到类型”AttachedPropertyInStyle。DerivedKeyBinding“
为什么会发生这种情况?我如何解决这个问题?
这个问题似乎与
Name
绑定——如果是静态值,代码将完美地执行。