我有一个TabControl,用户控件在TabItem内容中,如下所示:
\...
<TabItem.Content>
<vm:myUserControl />
</TabItem.Content>
\...
<TabItem.Content>
<vm:otherUserControl/>
</TabItem.Content>
当我更改otherUserControl
中的数据时,如何更新myUserControl
(例如在列表中添加必须显示在myUserControl
中的元素)。这些控件具有不同的数据上下文(来自不同的viem模型类,继承BaseViewModel
的是谁,实现INotifyPropertyChanged
的是谁)。数据由WCF客户端服务提供。谢谢你的帮助。
您可以使用Mediator/Messenger或EventAggregator。因此您的otherUsercontrol引发消息/事件,您的myUserControl订阅并对此消息/事件作出反应。
或者,如果你不想松散耦合,你当然可以直接耦合你的两个视图模型,并使用一些事件。
有很多方法可以实现这一点。一种方法是在otherUserControl
中激发一个事件,并在MainWindow
中订阅该事件,并允许MainWindow
更新myUserControl
。
MyUserControl XAML
<TextBlock x:Name="TextValue">Initial Text</TextBlock>
OtherUserControl XAML
<Button Click="Button_Click">Click Me</Button>
其他用户控制C#
public event EventHandler ButtonClicked;
private void Button_Click(object sender, RoutedEventArgs e)
{
if(this.ButtonClicked != null)
{
this.ButtonClicked(this, EventArgs.Empty);
}
}
主窗口XAML
<StackPanel>
<vm:MyUserControl x:Name="MyUserControl"/>
<vm:OtherUserControl x:Name="OtherUserControl"/>
</StackPanel>
主窗口C#
public MainWindow()
{
InitializeComponent();
this.OtherUserControl.ButtonClicked += OtherUserControl_ButtonClicked;
}
void OtherUserControl_ButtonClicked(object sender, EventArgs e)
{
this.MyUserControl.TextValue.Text = "Updated Text";
}
另一种选择是使用类似Prism事件聚合器的东西,它将允许MyUserControl
订阅OtherUserControl
引发的事件,而不需要MainWindow
设置两者之间的通信。对于较大的项目来说,这是一个更好的选择,因为它允许您的组件真正松散耦合。