【问题标题】:Object of type 'System.Windows.Data.Binding' cannot be converted to type 'System.Nullable`1[System.Guid]'“System.Windows.Data.Binding”类型的对象无法转换为“System.Nullable`1[System.Guid]”类型
【发布时间】:2013-12-28 02:48:52
【问题描述】:

here 提出的问题类似,但在这种情况下,此异常的原因似乎不同。也许我的属性设置有误?

我有一个要绑定的自定义用户控件。但是,InitializeComponent 会抛出错误 Object of type 'System.Windows.Data.Binding' cannot be converted to type 'System.Nullable 1[System.Guid]' VS 说它是抛出此错误的 set 属性。

我简化了我的属性以尝试查找错误,但它仍然会在没有任何设置器逻辑的情况下发生

public Guid? SelectedItemGUID
{
    get
    {
        if (SelectedItem == null) return null;
        else return (Guid)SelectedItem.GetType().GetProperty("GUID").GetValue(SelectedItem, null);
    }
    set
    {
        return;
    }
}

我在 XAML 中使用(client.BIllToClient 是 Guid?)进行绑定

SelectedItemGUID="{Binding Path=client.BillToClient, Mode=TwoWay}"

【问题讨论】:

    标签: c# wpf silverlight


    【解决方案1】:

    试试这个

    public static readonly DependencyProperty SelectedItemGUIDProperty = DependencyProperty.Register("SelectedItemGUID",typeof(Guid?),typeof(UserControl),new FrameworkPropertyMetadata(null));
    
        public Guid? SelectedItemGUID
        {
            public Guid? SelectedItemGUID
        {
            get { return (Guid?)GetValue(SelectedItemGUIDProperty); }
            set { SetValue(SelectedItemGUIDProperty, (Guid?)SelectedItem.GetType().GetProperty("GUID").GetValue(SelectedItem, null)); }
        }
        }
    

    我认为您正在尝试绑定简单的 CLR 属性。绑定需要 Target 作为 DependencyProperty Custom binding。我在上面的代码中将 typeof(UserControl) 作为父类型,将其替换为控件的类型。

    【讨论】:

    • 没错!我终于在你发帖前 5 分钟弄明白了。我以前从未使用过 DependencyProperties,但现在我对它们了如指掌。
    猜你喜欢
    • 2023-04-03
    • 2011-08-31
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 2022-01-13
    • 2022-11-04
    • 1970-01-01
    相关资源
    最近更新 更多