且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF MVVM:如何在用户控件上设置绑定?

更新时间:2022-05-20 02:57:15

SystemErrors 不是它的视觉祖先。 UserControl 。它是 DataContext ,因此只要 ErrorMessageModel 类具有公共属性,以下内容就绑定而言应该起作用 ErrorName 属性,返回您期望返回的结果:

SystemErrors is not a visual ancestor of the UserControl. It is the DataContext so the following should work as far as the binding is concerned provided that the ErrorMessageModel class has a public ErrorName property that returns what you expect it to return:

<TextBlock Text="{Binding ActiveError.ErrorName}"/>

以下内容将设置为 ErrorMessageModel 属性并引发 PropertyChanged 事件:

The following will however not set the ErrorMessageModel property and raise the PropertyChanged event:

_activeError = errors[index];

您应将属性设置为新的 ErrorMessageModel 对象:

You should set the property to a new ErrorMessageModel object:

public void SetActiveError(byte index)
{
    ActiveError = errors[index];
}

还请确保调用 SetActiveError 在XAML标记中创建的 SystemErrors 类的实际实例上的code>方法:

Also make sure that you call the SetActiveError method on the actual instance of the SystemErrors class that you create in your XAML markup:

<UserControl.DataContext>
    <e:SystemErrors/>
</UserControl.DataContext>