【问题标题】:UWP InvalidCastException when using XAML databinding使用 XAML 数据绑定时出现 UWP InvalidCastException
【发布时间】:2015-10-17 21:47:11
【问题描述】:

谁能解释如何评估 XAML 数据绑定表达式?我有一个带有注册属性 VisualState 的控件。

public CardStates VisualState
{
    get
    {
        return (CardStates)this.GetValue(VisualStateProperty);

    }
    set
    {
        this.SetValue(VisualStateProperty, value);
    }
}

public static readonly DependencyProperty VisualStateProperty = DependencyProperty.RegisterAttached("VisualStateProperty", typeof(CardStates), typeof(StateManager), new PropertyMetadata(null, (s, e) => { }));

在 xaml 中,我尝试将值绑定到此属性。状态存在父级的 DataContext 对象。

<local:CardControl  VisualState="{Binding State.Value}" />

XamlTypeInfo.g.cs 中生成的代码如下所示

private void set_4_CardControl_VisualState(object instance, object Value)
{
    var that = (global::MeetEric.UI.Controls.CardControl)instance;
    that.VisualState = (global::MeetEric.ViewModels.CardStates)Value;
}

此代码引发 InvalidCastException,因为 Value 的值是 Windows.UI.Xaml.Data.Binding 对象。

我是否遗漏了一些明显的东西来启用数据绑定?我需要某种形式的转换器吗?

【问题讨论】:

    标签: c# xaml winrt-xaml win-universal-app


    【解决方案1】:

    尝试将typeof(StateManager) 更改为typeof(CardControl)。 (在 DependencyProperty.RegisterAttached)

    此参数需要 DependencyProperty 的所有者。

    【讨论】:

      【解决方案2】:

      当您尝试将绑定与常规属性一起使用时会发生此错误。为了使绑定解析为正确的类型,您需要绑定到DependencyProperty

      正如其他人所提到的,您的语法有点偏离,这可能是导致问题的原因。

      这个错误肯定是非常神秘的。我只是在我自己的项目中使用它,但是一旦我将我的属性更改为依赖项,它就完美了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-12
        • 1970-01-01
        • 2023-03-30
        相关资源
        最近更新 更多