【发布时间】:2020-08-16 08:06:00
【问题描述】:
我正在尝试在 2 个不同的 Windows 中使用相同的用户控件。目标是如果用户控件中的某个控件发生更改,它将反映在使用相同用户控件的另一个窗口中。我的理解是它们不是“同步”的,因为每个窗口都有自己的用户控件实例。如何让两者使用相同的实例或相互同步?
为了更好地解释我需要帮助的内容,我创建了一个简单的项目并创建了 2 个 xaml 窗口——MainWindow 和 SecondWindow。我还创建了一个名为 CommonUC 的用户控件。
在 MainWindow 中,我还添加了一个按钮,单击该按钮可打开 SecondWindow。如果在 SecondWindow 中更改,是否有办法反映 MainWindow 中复选框的更改?
MainWindow.xaml:
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Test"
xmlns:uc="clr-namespace:Test.UserControls"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="200">
<Grid>
<uc:CommonUC/>
<Button Content="Button" HorizontalAlignment="Left" Margin="54,116,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</Grid>
MainWindow.xaml.cs:
namespace Test
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SecondWindow secondWindow = new SecondWindow();
secondWindow.Owner = System.Windows.Application.Current.MainWindow;
secondWindow.ShowDialog();
}
}
}
SecondWindow.xaml:
<Window x:Class="Test.SecondWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Test"
xmlns:uc="clr-namespace:Test.UserControls"
mc:Ignorable="d"
Title="SecondWindow" Height="200" Width="200">
<Grid>
<uc:CommonUC/>
</Grid>
CommonUC.xaml:
<UserControl x:Class="Test.UserControls.CommonUC"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Test.UserControls"
mc:Ignorable="d"
d:DesignHeight="50" d:DesignWidth="100">
<Grid>
<CheckBox Content="CheckMe"/>
</Grid>
【问题讨论】:
-
在 Internet 上搜索 MVVM 和 WPF 数据绑定。然后将两个(或更多)UserControl 实例的属性绑定到视图模型类的单个实例的属性。
-
尝试使用 MainWindow 的 CommonUc 实例在 Button_Click 方法上设置 SecondWindow 内的 CommonUC 元素。它应该可以工作。
标签: c# wpf xaml user-controls