與大多數事情的工程,有沒有正確和錯誤的答案,而這一切都取決於具體的方案。在後面的代碼中處理事件並適當地調用視圖模型非常好(如果實例化時您已將視圖模型的引用傳遞到視圖中)。
但是,您可以綁定到命令,我更喜歡這種方法,因爲它更鬆散耦合。此命令中的操作將設置您的型號(在此情況下,創建您的ReservationDataViewModel時傳入此實例)。
ReservationDataControl查看:
<Button Command={Binding ClickCommand}/>
ReservationDataControl視圖模型(數據上下文):現在
private readonly Statistics _statistics;
public ICommand ClickCommand { get; set; }
private ReservationDataViewModel(Statistics statistics)
{
_statistics = statistics;
InitialiseCommands();
}
private void InitialiseCommands()
{
ClickCommand = new RoutedUICommand("ClickCommand", "ClickCommand", typeof(ViewModel));
CommandBinding clickCommandBinding = new CommandBinding(ClickCommand, ExecuteClickCommand, ClickCommandCanExecute);
CommandManager.RegisterClassCommandBinding(typeof(ViewModel), clickCommandBinding);
}
private void ExecuteClickCommand(object sender, ExecutedRoutedEventArgs args)
{
// perform click logic here...
// e.g. say there is a property on your statistics called 'ReservationCount'
// the command adds a reservation (increments the count)
_statistics.ReservationCount += 1;
}
private void ClickCommandCanExecute(object sender, CanExecuteRoutedEventArgs args)
{
args.CanExecute = true; // put your can execute logic here...
}
,如果你的模型(即統計類)設置正確,它應該有一個告訴任何關心它已經改變的代碼的方式。
即
public class Statistics
{
public event EventHandler ReservationCountChanged;
private int _reservationCount;
// think about how you may restrict set access for this model
public int ReservationCount
{
get { return _reservationCount; }
protected set
{
if (_reservationCount != value)
{
_reservationCount = value;
if (ReservationCountChanged != null)
ReservationCountChanged(this, new EventArgs());
}
}
}
public Statistics() { }
}
現在,您PartyStatsViewModel可以在這個變化回暖,源於ReservationDataViewModel和更新的觀點與標準的WPF綁定實現。
PartyStatsControl視圖模型:
private readonly Statistics _statistics;
public int ReservationCount
{
get { return _statistics.ReservationCount; }
set
{
_statistics.ReservationCount = value;
OnPropertyChanged("ReservationCount");
}
}
public PartyStatsControlViewModel(Statistics statistics)
{
_statistics = statistics;
_statistics.ReservationCountChanged += OnReservationCountChanged;
}
private void OnReservationCountChanged(object sender, RoutedEventArgs args)
{
// todo: force this onto the UI thread or exceptions will occur
this.ReservationCount = ((Statistics)sender).ReservationCount;
}
這只是什麼樣的事件聚合被造的。您也可以使用rx公開服務,具體取決於您的設計。 –
單個事件的事件和EventAggregator之間有什麼區別? –
一個是分離的,另一個不是。 –