基于MainWindow事件更新viewmodel
我有一个UdpClient,在我的MainWindow上触发一个DataRecevied事件:
public partial class MainWindow : Window
{
public static YakUdpClient ClientConnection = new YakUdpClient();
public ClientData;
public MainWindow()
{
InitializeComponent();
Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
ClientData = new ClientData();
ClientConnection.OnDataReceived += ClientConnectionOnDataReceived;
}
private void ClientConnectionOnDataReceived(object sender, MessageEventArgs messageEventArgs)
{
ClientData.Users = messageEvenArgs.ConnectedUsers;
}
}
我的ClientData和User类看起来如下所示:
public class ClientData
{
public List<User> Users {get;set;)
}
public class User
{
public string Name {get;set;}
}
在我的MainWindow中,我有一个名为UserListView
的UserControl,它具有一个名为UserListViewModel
的ViewModel
ViewModel如下所示:
public class UserListViewModel: BindableBase
{
public UserListViewModel()
{
//I am sure there are better ways of doing this :(
Users = new ObservableCollection<User>((MainWindow)Application.Current.MainWindow).ClientData.Users
});
private ObservableCollection<User> _users;
public ObservableCollection<User> Users
{
get{ return _users;}
set { this.SetProperty(ref this._users, value); }
}
}
我在这里遇到的困难是,当MainWindow上的ClientConnectionOnDataReceived
事件被触发时,我想更新我的ClientData
类,然后应该以某种方式通知My Viewmodel列表已更改,然后更新我的UI。
任何人都可以给我一个如何在WPF中使用MVVM(Prism)来实现这一目标的可靠示例吗?
我是MVVM的新手,所以我仍然试图解决这个问题。
首先,主窗口应该进行订阅的原因没有明显的原因。
我会去做这样的事情:
INotifyPropertyChanged
(通知消费者对Users
进行更改) UserListViewModel
并观察Users
属性(请参阅PropertyObserver) Users
在服务的变化,更新Users
在用户列表视图模型 最重要的是,这里不需要ObservableCollection
:-)
编辑:例如:
interface IUserService : INotifyPropertyChanged
{
IReadOnlyCollection<User> Users
{
get;
}
}
class YakUdpService : BindableBase, IUserService
{
private readonly YakUdpClient _yakUdpClient;
private IReadOnlyCollection<User> _users;
public YakUdpService()
{
_yakUdpClient = new YakUdpClient();
_yakUdpClient.OnDataReceived += ( s, e ) => Users = e.ConnectedUsers;
}
public IReadOnlyCollection<User> Users
{
get
{
return _users;
}
private set
{
SetProperty( ref _users, value );
}
}
}
class UserListViewModel : BindableBase
{
private IReadOnlyCollection<UserViewModel> _users;
private readonly IUserService _userService;
private readonly PropertyObserver<IUserService> _userServiceObserver;
public UserListViewModel( IUserService userService )
{
_userService = userService;
_userServiceObserver = new PropertyObserver<IUserService>( userService );
_userServiceObserver.RegisterHandler( x => x.Users, () => Users = _userService.Users.Select( x => new UserViewModel( x ) ).ToList() );
// ^^^ should use factory in real code
}
public IReadOnlyCollection<UserViewModel> Users
{
get
{
return _users;
}
private set
{
SetProperty( ref _users, value );
}
}
}
然后注册服务
Container.RegisterType<IUserService, YakUdpService>( new ContainerControlledLifetimeManager() );
在你的引导程序或你的模块的初始化。
链接地址: http://www.djcxy.com/p/39545.html