c# - 当其他属性正常工作时,WPF 绑定(bind)错误到类属性

标签 c# wpf mvvm

我知道还有很多其他类似的 SO 帖子,但似乎没有一个有我绑定(bind)到类属性的场景,并且其他属性工作得很好。我正在使用 MVVM 模式,我的 View 模型在 c++/cli 中.由于其他属性有效,它不是我的DataContext我的观点。我有一个 IsEnabledButton绑定(bind)到我的 ViewModel 中的 bool 值。现在,当尝试绑定(bind)到类似的东西时,

private:
bool thing = false;
public:
bool Thing
{
    bool get() { return thing; }
    void set(bool value) { thing = value; }
}

它工作得很好。但后来我做了类似的事情,
public ref class MyThingClass
{
    private:
    bool isEnabled = false;
    public:
    bool IsEnabled
    {
        bool get() { return thing; }
        void set(bool value) { thing = value; }
    };
};

public:
//Not sure if I need a handle (^) on this or not
MyThingClass MyThing;


//XAML
<Button x:Name="MyButton" IsEnabled="{Binding MyThing.IsEnabled}"/>

某些东西决定中断,属性没有绑定(bind),在输出中我得到 System.Windows.Data Error: 40 : BindingExpression path error: 'MyThing ' property not found on 'object' ''MyViewModel' (HashCode=66641179)'. BindingExpression:Path=MyThing.IsEnabled; DataItem='MyViewModel' (HashCode=66641179); target element is 'Button' (Name='MyButton'); target property is 'IsEnabled' (type 'Boolean')
如果我遗漏了任何内容,或者没有任何意义,请提出问题。

最佳答案

当你写:

MyThingClass MyThing;

您创建一个名为 MyThing 的公共(public)字段,而不是属性。

为了使用数据绑定(bind),需要将其定义为属性,而不是字段:
property MyThingClass^ MyThing;

此外,如果您希望属性更新 UI,您的 MyThingClass将需要实现 INotifyPropertyChanged .还要注意句柄类型( ^ )的需要,因为它是一个托管类。

关于c# - 当其他属性正常工作时,WPF 绑定(bind)错误到类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41353937/

相关文章:

c# - Usercontrol不同控件属性访问

c# - 为Caliburn.Micro Action Message指定自定义防护属性

android - MVVM。如何将复杂的数据/命令从域传输到 View

c# - 有人可以提供快速的 App.config/Web.config 教程吗?

c# - TFS Rest API 查询

c# - 在返回空 200 响应的 WebAPI 操作方法中抛出 HttpResponseException

c# - WPF 使用语句打开另一个窗体

c# - 如何在属性网格中显示动态对象?

c# - 如何剪掉重叠区域?

android - 错误 : [Dagger/MissingBinding] *. AuthRepository 不能在没有 @Provides 注释的方法的情况下提供