在我的其他帖子中回答了问题,但我没有得到完整答案。我做了一些走动和它的工作,但我对此不太满意。 所以我想知道如何在MVVM模式中做到这一点。
我在View中的文本框中更新值时遇到了非常令人沮丧的问题。 Proprerty消息正在从我的回调更新,但它没有在GUI中显示。属性正确绑定。现在我可以做到这一点。原因是我不在UI线程上引发PropertyChanged,因为我从回调中调用它。我正在努力,但没有任何作用。如何在UI线程上引发PropertyChange事件?
再次编辑更新代码:
namespace test
{
public class MainViewModel : INotifyPropertyChanged, IDataExchangeCallback
{
public MainViewModel()
{
Message = "TEST1";
}
void IDataExchangeCallback.Result(string result)
{
Message += result;
}
public void Register()
{
InstanceContext instanceContext = new InstanceContext(new MainViewModel());
DataExchangeClient client = new DataExchangeClient(instanceContext);
client.RegisterClient(Guid.NewGuid().ToString());
}
private string _message;
public string Message
{
get { return this._message; }
set
{
if (this._message != value)
{
this._message = value;
OnPropertyChanged("Message");
}
}
}
public event PropertyChangedEventHandler PropertyChanged; //ALWAYS NULL!!! BUT I HAVE INotifyPropertyChanged implement
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
Application.Current.Dispatcher.Invoke(() =>
handler(this, new PropertyChangedEventArgs(name)));
}
}
}
}
我的PropertChange始终为空。为什么?当我使用绑定时,它会订阅PropertyChanged。
修改 我仍然需要帮助
答案 0 :(得分:0)
找到解决方案!
显然,如果你想使用INotifyPropertyChanged,你需要在代码中将其称为显式。
this.DataContext = mvm;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
MainViewModel mvm = new MainViewModel();
mvm.Register();
this.DataContext = mvm; //this you need
}
}
XAML中的声明是不够的:
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
如果有人能解释我为什么会感激?