Communication between two user controls (one conta

2019-06-11 12:52发布

问题:

I'm developing a WPF with MVVM, .NET Framework 4.6.1 and C#.

I have two user controlers, one inside the other one:

<Grid x:Name="gridStartBatch" Margin="30" Grid.RowSpan="6" Grid.ColumnSpan="3" Visibility="{Binding GridStartBatchVisibility}">
    <local:StartBatch x:Name="userControlStartBatch" />
</Grid>

I show StartBatch user control changing GridStartBatchVisibility value.

On StartBatchViewModel I have three properties that I want to pass to FirstControlViewModel and also I want to notify FirstControlViewModel to change GridStartBatchVisibility value to hide StartBatch.

Is there anyway to access FirstControlViewModel from StartBatchViewModel?

回答1:

There are many ways to communicate between view models and a lot of points what the point is the best. You can see how it is done:

  • using MVVMLight

  • in Prism

  • by Caliburn

In my view, the best approach is using EventAggregator pattern of Prism framework. The Prism simplifies MVVM pattern. However, if you have not used Prism, you can use Rachel Lim's tutorial - simplified version of EventAggregator pattern by Rachel Lim. I highly recommend you Rachel Lim's approach.

If you use Rachel Lim's tutorial, then you should create a common class:

public static class EventSystem
{...Here Publish and Subscribe methods to event...}

And publish an event into your OptionViewModel:

eventAggregator.GetEvent<ChangeStockEvent>().Publish(
new TickerSymbolSelectedMessage{ StockSymbol = “STOCK0” });

then you subscribe in constructor of another your MainViewModel to an event:

eventAggregator.GetEvent<ChangeStockEvent>().Subscribe(ShowNews);

public void ShowNews(TickerSymbolSelectedMessage msg)
{
   // Handle Event
}

The Rachel Lim's simplified approach is the best approach that I've ever seen. However, if you want to create a big application, then you should read this article by Magnus Montin and at CSharpcorner with an example.



标签: c# wpf mvvm