C# 框架正在损坏WPF附加属性的类型

C# 框架正在损坏WPF附加属性的类型,c#,wpf,xaml,attached-properties,C#,Wpf,Xaml,Attached Properties,考虑一些派生类型的标准附加属性: public class DerivedKeyBinding : KeyBinding { public string Name; //shortened, make this propdp } public class KeyBindingExtenstions { public static DerivedKeyBinding GetCommand(DependencyObject obj) { return (Derive

考虑一些派生类型的标准附加属性:

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=GetCommandd上崩溃;由于本地原因导致的行:DerivedKeyBinding在进程中的某个位置丢失给KeyBinding。 出于某种奇怪的原因,DerivedKeyBinding类型的属性被设置为KeyBinding类型的值,即使在XAML中该值被显式设置为DerivedKeyBinding

System.InvalidCastException:'无法将类型为'System.Windows.Input.KeyBinding'的对象强制转换为类型为'AttachedPropertyInStyle.DerivedKeyBinding'

为什么会发生这种情况?我如何解决此问题

这个问题似乎与名称绑定有关——如果是静态值,则代码将完美地执行。

覆盖。发件人:

继承人须知

每个Freezable派生类都必须实现此方法。典型的实现是简单地调用默认构造函数并返回结果

在PropertyChangedCallback中,您还可以写入:

var commandValue = (DerivedKeyBinding)e.NewValue;

看来我需要找到一些手动的Derving框架类101。谢谢你的回答。
var commandValue = (DerivedKeyBinding)e.NewValue;