我试着寻找答案,寻找类似的问题,但我找不到任何适合这种情况的东西。
我有一个类似这样的MainWindow (省略了一些部分):
<Window x:Class="test.MainWindow"
xmlns:local="clr-namespace:test"
xmlns:Views="clr-namespace:test.Views">
<Grid>
<DockPanel>
<StatusBar>
<StatusBarItem>
<Views:ProfileView />
</StatusBarItem>
<Separator />
<StatusBarItem>
<Views:StatusView />
</StatusBarItem>
</StatusBar>
</DockPanel>
</Grid>
</Window>使用代码隐藏:
using System.Windows;
namespace test
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
// some stuff done here
}
}和两个UserControl:
<UserControl x:Class="test.Views.StatusView"
xmlns:local="clr-namespace:test.Views"
xmlns:ViewModels="clr-namespace:test.ViewModels">
<UserControl.DataContext>
<ViewModels:StatusViewModel/>
</UserControl.DataContext>
<Grid>
<Border>
<TextBlock Text="{Binding Status}" />
</Border>
</Grid>
</UserControl>和:
<UserControl x:Class="test.Views.ProfileView"
xmlns:local="clr-namespace:test.Views"
xmlns:ViewModels="clr-namespace:test.ViewModels" MouseEnter="UserControl_MouseEnter" MouseLeave="UserControl_MouseLeave">
<UserControl.DataContext>
<ViewModels:ProfileViewModel/>
</UserControl.DataContext>
<Grid>
// some stuff done here
</Grid>
</UserControl>使用代码隐藏:
using System.Windows.Controls;
namespace test.Views
{
public partial class StatusView : UserControl
{
public StatusView()
{
InitializeComponent();
}
}
}和:
using System.Windows.Controls;
namespace test.Views
{
public partial class ProfileView : UserControl
{
public ProfileView()
{
InitializeComponent();
}
private void UserControl_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
// Update status bar text
}
private void UserControl_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
// Update status bar text
}
}
}每个UserControl都有自己的ViewModel设置为DataContext:
using System;
using System.ComponentModel;
namespace test.ViewModels
{
class StatusViewModel : INotifyPropertyChanged
{
private string _status = string.Empty;
public string Status
{
get { return _status; }
set { _status = value; OnPropertyChanged("Status"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
public StatusViewModel() { }
}
}和:
using System;
namespace test.ViewModels
{
class ProfileViewModel
public ProfileViewModel() { }
// some stuff done here
}
}正如您从代码中看到的,ProfileView有MouseEnter和MouseLeave事件,我希望在StatusView中对它们设置TextBlock.Text值(通过它的ViewModel.Status属性)。
现在这里没有显示,但是,其他类也应该能够使用相同的原则,以线程安全的方式更新状态栏的值。
我该如何做到这一点呢?
我想过使用DependencyPropertyes或委托和事件,但不知道怎么做,因为目前,UserControls (和其他)都是通过MainWindow中的XAML实例化的,而不是通过代码隐藏。我认为这就是我应该如何做的(如果我遵循MVVM,并有工作分离-设计师是设计,而程序员是编程),但这正是我不知道如何解决这个问题的原因。
谢谢你的帮助。
发布于 2016-11-24 19:45:59
我强烈推荐使用MVVM Light。
您可以使用MVVM Light Messenger。它是一个允许在对象之间交换消息的类。Messenger类主要用于视图模型之间的消息发送:http://dotnetpattern.com/mvvm-light-messenger
PS:我还建议使用命令绑定,而不是事件处理程序(这不是MVVM式的)。
https://stackoverflow.com/questions/40785277
复制相似问题