我有一个类库,其中包含一个实现 的基类 ( 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
类中。
我需要做什么才能让它发挥作用?
// 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));
}
}
// 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");
});
});
}
}
// 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");
});
});
}
}
<TextBlock Text="{Binding TestProp}" Style="{StaticResource NaviHeading}" />
为了让 Fody 注入外部组件,您必须指定合适的织布工。
为了指示织布机运行的内容以及在项目级别使用 FodyWeavers.xml 文件的顺序。需要手动添加。它采用以下形式:
<Weavers>
<PropertyChanged />
</Weavers>
见https://github.com/Fody/PropertyChanged#add-to-fodyweaversxml
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句