C# 从接口更新属性
我有一个与属性的接口:C# 从接口更新属性,c#,C#,我有一个与属性的接口: public interface IMyInterface { string Test { get; set; } } public ViewModel { // ... public string Test { get { return _myInterface.Test; } set {_myInterface.Test = value } } } 下面是实现它的类:
public interface IMyInterface
{
string Test { get; set; }
}
public ViewModel
{
// ...
public string Test
{
get { return _myInterface.Test; }
set {_myInterface.Test = value }
}
}
下面是实现它的类:
public MyClass : IMyInterface
{
private string _test;
public string Test
{
get { return _test; }
set
{
_test = value;
RaisePropertyChanged("Test");
}
}
Public void MethodName()
{
//Logic that updates the value for Test
}
}
到目前为止一切正常,当调用该方法时,Test
会得到更新
我还有一个ViewModel,它在构造函数中实现了IMyInterface
private IMyInterface _myInterface;
public ViewModel(IMyInterface myinterface)
{
_myInterface = myinterface;
}
是否可以在我的
ViewModel
中有一个属性,每当Test
的值更改时,该属性都会更新 您不一定需要一个新字段-您可以做的只是将另一个属性添加到ViewModel中,以重新公开您的组合接口属性:
public interface IMyInterface
{
string Test { get; set; }
}
public ViewModel
{
// ...
public string Test
{
get { return _myInterface.Test; }
set {_myInterface.Test = value }
}
}
编辑、重新引发属性更改事件
我建议您要求IMyInterface
extendsINotifyPropertyChanged
public interface IMyInterface : INotifyPropertyChanged
{
string Test { get; set; }
}
然后由底层的具体类实现,如下所示:
public class MyClass : IMyInterface
{
private string _test;
public string Test
{
get { return _test; }
set
{
_test = value;
RaisePropertyChanged("Test");
}
}
private void RaisePropertyChanged(string propertyName)
{
// Null means no subscribers to the event
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
您可以只向界面添加一个事件。你想重新发明WPF依赖属性吗?@HansPassant,你介意演示如何向我的界面添加事件吗?我一直在四处寻找,但很难找到一个适合我的VM需要的例子。谢谢,谢谢你的回答!我将您的代码添加到我的VM中,并调用了更新MyClass中属性的方法。由于某些原因,VM中的属性没有被命中。我设置了一个断点,但虚拟机似乎没有意识到更改?我可能遗漏了什么吗?ViewModel将始终与其
\u myInterface
字段同步,这仅仅是因为它“通过”组合的\u myInterface
属性。如果除保持属性“同步”外,还需要通知事件,则根据Hans的评论,还需要在界面上公开并发布INotifyPropertyChanged
事件。