c# - 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}" />
解决方案
为了让 Fody 注入外部组件,您必须指定适当的编织者。
为了指示在项目级别使用 FodyWeavers.xml 文件的顺序以及运行的编织程序。需要手动添加。它采用以下形式:
<Weavers>
<PropertyChanged />
</Weavers>
请参阅https://github.com/Fody/PropertyChanged#add-to-fodyweaversxml
推荐阅读
- javascript - Javascript clearInterval 不适用于变量
- ios - 在 ios 中使用 UIImagePickerViewController 裁剪视频文件
- angular - 从 SnackBar 组件撤消操作
- caching - MSI、MESI、MOSI、MOESI 和 MESIF 有哪些缓存一致性协议?
- c++ - C++ 调整动态数组的大小最多可以处理一定数量的元素,但在某些时候崩溃并出现错误 (0XC0000005)
- ruby - Ruby:为什么 unpack('Q') 给出的结果与手动转换不同?
- javascript - 在组件之间传递数据 React-JS
- javascript - 在特定点停止 java 脚本画布中的对象
- javascript - jQuery在页面上显示文本输入
- python - Python - 返回2个队列的组合