我从事WPF MVVM项目。我正在努力将自己的ViewModelMainWindow
与usercontrol
放置在里面的ViewModel之间进行交流MainWindow
。
所以我有:
用户控件
主窗口
MainWindowViewModel
我的UserControl非常简单:
<Grid MouseDown="UIElement_OnMouseDown">
<Rectangle Fill="BlueViolet" />
</Grid>
在代码后面(仅在单击矩形时引发一个事件,并传递坐标):
public partial class FooUserControl : UserControl
{
public FooUserControl()
{
InitializeComponent();
}
public event EventHandler<BarEventArgs> BarClick;
private void UIElement_OnMouseDown(object sender, MouseButtonEventArgs e)
{
double x = e.GetPosition(this).X;
double y = e.GetPosition(this).Y;
string value_to_pass = "[" + x + "," + y + "]";
BarEventArgs bar = new BarEventArgs() { Bar = 2, Foo = value_to_pass };
BarClick?.Invoke(sender, bar);
}
}
我的MainWindow没有代码隐藏。只是xaml。如您所见,我通过Command将click事件传递给MainWindowViewModel:
<Window.DataContext>
<viewModels:MainWindowViewModel />
</Window.DataContext>
<Grid>
<local:FooUserControl>
<i:Interaction.Triggers>
<i:EventTrigger EventName="BarClick">
<cmd:EventToCommand Command="{Binding ClickedCommand}" PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
</local:FooUserControl>
</Grid>
最后我的MainWindowViewModel仅具有以下命令:
public class MainWindowViewModel : ObservableObject
{
public ICommand ClickedCommand => new RelayCommand<BarEventArgs>(o => Clicked(o.Foo));
private void Clicked(string a)
{
Debug.WriteLine("Clicked " + a);
}
}
因此,通过命令从UserControl的视图到MainWindow的视图模型的通信非常有效。但是,我该如何以相反的方式交流?从MainWindowViewModel到UserControl的视图?
您的ViewModels不应直接访问您的视图。他们根本不关心视图。他们所做的就是提供属性以使数据可用。视图现在可以绑定到这些属性。
因此,从ViewModel到View的所有通信仅通过绑定进行。当ViewModel必须告诉View某些信息时,它提供了一个属性。然后,取决于View绑定到该属性并对其执行操作-不管是什么。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句