代码之家  ›  专栏  ›  技术社区  ›  wondra

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

  •  0
  • wondra  · 技术社区  · 7 年前

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

    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 绑定——如果是静态值,代码将完美地执行。

    0 回复  |  直到 7 年前
        1
  •  1
  •   Community Mohan Dere    6 年前

    推翻 Key​Binding.​Create​Instance​Core 从…起 Microsoft Docs :

    继承人须知 

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


    public class DerivedKeyBinding : KeyBinding
    {
        ...
    
        protected override Freezable CreateInstanceCore()
        {
            return new DerivedKeyBinding();
        }
    }
    

    在PropertyChangedCallback中,您还可以写:

    var commandValue = (DerivedKeyBinding)e.NewValue;