我有一个类库,其中包含一个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}" />