如何从代码隐藏或通过绑定刷新WPF中的自定义用户控件



我有一个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设置两者之间的通信。对于较大的项目来说,这是一个更好的选择,因为它允许您的组件真正松散耦合。

最新更新