我正在开发我正在使用MVVM模式的项目。
我有一个文本框:
<TextBox Height="23" HorizontalAlignment="Right" Margin="0,30,72,0" Name="textBox1"
Text="{Binding Path=Rspchange, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True}" VerticalAlignment="Top" Width="75" />
和标签:
<Label Content="{Binding Path=LF, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Height="24" HorizontalAlignment="Left" Margin="540,3,0,0" Name="lbLF" VerticalAlignment="Top" Width="84" />
这里我分别使用了属性Rspchange和LF的双向绑定。
public UInt16 Rspchange
{
get
{
return this.eObj.GetRsBaseline(this.index);
}
set
{
this.eObj.SetRsBaseline(value, this.Index);
this.OnPropertyChanged(new PropertyChangedEventArgs("Rspchange"));
this.eObj.writedata(DefaultFileName);
}
}
public string LF
{
get
{
return this.eObj.LFrequency;
}
set
{
this.eObj.LFrequency = value;
this.OnPropertyChanged(new PropertyChangedEventArgs(" LF"));
}
}
在模特方面,我有这样的礼节:
public override string LFrequency
{
get { return configObject.lnFrequency.ToString(); }
set { configObject.lnFrequency = Convert.ToByte(value); }
}
public override UInt16 GetRsBaseline(int channelIndex)
{
return (byte)this.configObject.CConfig[index].Bline;
}
public override void SetRsBaseline(UInt16 value, int index)
{
byte[] arr = BitConverter.GetBytes(value);
this.configObject.CConfig[index].Bline = arr[0];
}
public byte Bline
{
get { return this.bline; }
set { this.bline = value; }
}
public byte lnFrequency
{
get { return this.ln_frequency; }
set { this.ln_frequency = value; }
}
我的应用程序通过串口与其他应用程序进行通信。我从其他应用程序获取数据,并且基于此我还必须更新我的GUI。
当我调试我的代码时,我已经看到我从其他应用程序获得更新的值到ln_frequency和bline但是它没有更新我的GUI。
请告诉我我的代码有什么问题,以便我从其他应用程序获取数据后可以更新我的GUI。
P.S:writexmldata的代码
public void WriteXmlData(string path)
{
if ((ie.Current as XElement).Attribute("name").Value == "Bline")
{
(ie.Current as XElement).Attribute("value").Value = this.channel_config[0].Bline.ToString();
}
if ((ie.Current as XElement).Attribute("name").Value == "LFrequency")
{
(ie.Current as XElement).Attribute("value").Value = this.lnFrequency.ToString();
}
}
这里我的目的是保存Bline和LFrequency的当前值,这样当用户再次启动我的应用程序时,用户将始终获得GUI的最新值。
答案 0 :(得分:1)
好的,你有你的xaml View,一个包含Rspchange和LF属性的ViewModel,以及一个包含LFrequency,Bline和lnFrequency属性的模型。
您了解Rspchange上的更新将更新您的UI,因为该行:
this.OnPropertyChanged(new PropertyChangedEventArgs("Rspchange"));
它基本上对用户界面说:“如果你关心,我会更新我的Rspchange属性”。由于存在双向绑定,因此UI会从viewModel中读取新值。
现在很清楚,如果您更新lnFrequency或Bline,则不会更新任何内容,因为其setter中没有通知。
我认为你在MVVM的实现中跳了几步,本文应该可以帮助你改进它:WPF MVVM INotifyPropertyChanged Implementation - Model or ViewModel
总之,您需要的是模型通知您的ViewModel已更新的方法。但是,如果不使用INotifyPropertyChanged来实现它,将更符合MVVM。因此,你可以认为lnFrequency和Bline实际上是你的viewModel的一部分,或者为它们创建一个新的ViewModel,或者使用任何类型的经典事件来围绕你的解决方案传播“由外部系统更新的模型”。