用户控件的XAML相同,但代码隐藏不同

本文关键字:代码 隐藏 控件 XAML 相同 用户 | 更新日期: 2023-09-27 18:25:16

WPF中有3个用户控件,它们有相同的布局(几个按钮和一个listview),但后面的代码不同,因为listview列出了不同类的集合。

是否可以以某种方式对三个用户控件使用相同的XAML?因为现在,如果我对一个XAML的布局进行更改,我必须手动对另外两个进行更改。

感谢

用户控件的XAML相同,但代码隐藏不同

这是MVVM 的完美场景

创建单个UserControlView

创建三个不同的后端类,用作ViewModel

对于UserControl的每个实例,使用不同的ViewModel作为DataContext

1)将通用XAML提取到单独的XAML文件中,然后在目标控件中将其用作DataTemplate:

    <!-- 1. CommonView.xaml would contains common XAML -->
    <!-- 2. Below is XAML of the any of three control -->    
    <UserControl>
        <!-- In three controls use shared XAML as data template -->
        <UserControl.Resources>
            <DataTemplate x:Key="sharedTemplate">
                <views:CommonView />
            </DataTemplate>
        </UserControl.Resources>
        <MyControl>
           <ContentPresenter ContentTemplate="{StaticResource sharedTemplate}" />
        </MyControl>
    </UserControl>

2) 将每个控件绑定到一个单独的ViewModel