首页 > 解决方案 > PropertyChanged 不会从不同程序集中的类中触发

问题描述

我有一个类库,其中包含一个BaseViewModel实现 的基类 ()INotifyPropertyChanged和一个派生自它的类 ( TestExternal)。

我使用 Fody v4.2.1 和 PropertyChanged.Fody v2.6.1。

在 WPF 应用程序中,我将该类用作 DataContext。更改属性时,它不会反映在应用程序中。TestInternal但是,如果我将该类从类库复制(并重命名为)到应用程序,则属性更改会反映在应用程序中。该类TestInternal派生自BaseViewModel类库中的相同类。

此简化示例中的类由 astring和组成ObservableCollection<string>

ObservableCollection<string>绑定到控件,并且在这两种情况下,添加元素都会"d"正确反映在应用程序中。但是将字符串属性设置"C"为仅反映在TestInternal类中。

我需要做什么才能使它正常工作?

BaseViewModel.cs

// This class is in the class library
public class BaseViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = (sender, e) => { };

    public void OnPropertyChanged(string name)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
}

测试外部.cs

// This class is in the class library
public class TestExternal : BaseViewModel
{
    public ObservableCollection<string> UserProjects { get; set; }
    public string TestProp { get; set; }
    System.Windows.Application App;

    public TestExternal(System.Windows.Application app)
    {
        this.App = app;
        UserProjects = new ObservableCollection<string>(new List<string>() { "a", "b", "c" });
        TestProp = "A";

        Task.Factory.StartNew(() =>
        {
            Thread.Sleep(5000);
            App.Dispatcher.Invoke((Action)delegate
            {
                TestProp = "C";
                UserProjects.Add("d");
            });
        });
    }
}

测试内部.cs

// This class is in the WPF app project
public class TestInternal : BaseViewModel
{
    public ObservableCollection<string> UserProjects { get; set; }

    public string TestProp { get; set; }

    System.Windows.Application App;

    public TestInternal(System.Windows.Application app)
    {
        this.App = app;
        UserProjects = new ObservableCollection<string>(new List<string>() { "a", "b", "c" });
        TestProp = "A";

        Task.Factory.StartNew(() =>
        {
            Thread.Sleep(5000);
            App.Dispatcher.Invoke((Action)delegate
            {
                TestProp = "C";
                UserProjects.Add("d");
            });
        });
    }
}

XAML

<TextBlock Text="{Binding TestProp}" Style="{StaticResource NaviHeading}" />

标签: c#wpfvisual-studio-2017fody-propertychanged

解决方案


为了让 Fody 注入外部组件,您必须指定适当的编织者。

为了指示在项目级别使用 FodyWeavers.xml 文件的顺序以及运行的编织程序。需要手动添加。它采用以下形式:

<Weavers>
    <PropertyChanged />
</Weavers>

请参阅https://github.com/Fody/PropertyChanged#add-to-fodyweaversxml


推荐阅读