我正在尝试将来自 ModelA 的消息添加到 ModelB 上的列表框
1.- 每当 ModelA 上发生触发时,
型号A
public string Message
{
get => _Message;
set
{
SetProperty(ref _Message, value);
if (!string.IsNullOrWhiteSpace(_Message))
{
SendMsgtoModelB(_Message);
}
}
}
private string _Message;
public void SendMsgtoModelB(string strFaultMessage)
{
ModelB.ModelMessage(strFaultMessage);
}
2.- 我将消息传输到 ModelB 获取消息 型号B
// string container
public string StrModelMsg
{
get => _StrModelMsg;
set => SetProperty(ref _StrModelMsg, value);
}
private string _StrModelMsg;
// receive string add to local string
public void ModelMessage(string strMsg)
{
strModelMsg = strMsg;
}
3.- 将消息添加到 ModelB 的视图列表框 模型视图B
// 使用可观察集合
public MsgCollection MsgObject { get; set; } = new MsgCollection();
public class MsgCollection : ObservableCollection<MsgObject>
{
// some wrapper functions for example:
public void Add(string msg)
{
this.Add(new MsgObject { MsgLog = msg});
}
}
// by implementing the INotifyPropertyChanged, changes to properties
// will update the listbox on-the-fly
public class MsgObject : INotifyPropertyChanged
{
private string _msg;
// a property.
public string MsgLog
{
get { return _msg; }
set
{
if (_msg != value)
{
_msg = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(MsgLog)));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
4.- ModelB 视图 XAML 模型视图
<Grid Margin="10" HorizontalAlignment="Stretch" ShowGridLines="True">
<ListBox Name="lbOperatorHistory" HorizontalAlignment="Stretch" HorizontalContentAlignment="Left" ItemsSource="{Binding MsgObjectCollection, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="MsgLog">
</ListBox>
</Grid>
5.- 每次触发 ModelB 视图时,我都需要一种方法来记录来自 ModelA 的消息
6.- 我可以在构造函数上添加静态项,如下所示; 查看模型
public MsgCollection MsgObjectCollection { get; set; } = new MsgCollection();
public ViewModelB()
{
ModelB = new(logger);
MsgObjectCollection.Add(new MsgObject { MsgLog= "ViewModel Test"});
}
6.-我需要一种方法来添加此消息,每当这些消息在 ModelA 到 ModelB 视图上触发时
我同意之前发帖者的观点,这个问题很难理解。
但是您可能对集合属性有典型的 INotifyPropertyChange 误解:
在 ViewModel 中,在构造时您实际上设置了 MsgCollection 属性,并且这是该属性唯一实际更改的时间。当您将对象添加到此集合时,属性本身不会更改,因此不会触发 PropertyChange 事件。反过来,视图不会知道有东西需要更新。
每当您向 MsgCollection 添加内容时,您应该添加一行类似
RaisePropertyChanged(nameof(MsgCollection));