WPF之TabControl控件用法

本文介绍了一个使用 WPF 的 TabControl 显示不同部门员工信息的例子。通过创建实体基类 NotificationObject 和继承该类的 Employee 与 Department 类,实现了属性更改通知机制。XAML 中定义了 DataGrid 的样式以展示数据,并设置了 TabItem 来呈现每个部门的信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先创建实体基类:NotificationObject(用来被实体类继承) 实现属性更改通知接口:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace TabControlDemo
{
    public class NotificationObject:INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged!=null)
            {
                this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
View Code

 

创建员工类Employee继承NotificationObject类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TabControlDemo
{
    public class Employee:NotificationObject
    {
        private string employeeName;

        public string EmployeeName
        {
            get { return employeeName; }
            set
            {
                if (value!=employeeName)
                {
                    employeeName = value;
                    OnPropertyChanged("EmployeeName");
                }
            }
        }

        private string sex;

        public string Sex
        {
            get { return sex; }
            set
            {
                if (value != sex)
                {
                    sex = value;
                    OnPropertyChanged("Sex");
                }
            }
        }

        private int age;

        public int Age
        {
            get { return age; }
            set
            {
                if (value != age)
                {
                    age = value;
                    OnPropertyChanged("Age");
                }
            }
        }

        private string title;

        public string Title
        {
            get { return title; }
            set
            {
                if (value != title)
                {
                    title = value;
                    OnPropertyChanged("Title");
                }
            }
        }
    }
}
View Code

 

创建部门类Department继承NotificationObject类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace TabControlDemo
{
   public class Department:NotificationObject
    {
        private string name;

        public string Name
        {
            get { return name; }
            set 
            {
                if (value!=name)
                {
                    name = value;
                    OnPropertyChanged("Name");
                }
            }
        }

        private ObservableCollection<Employee> employees;

        public ObservableCollection<Employee> Employees
        {
            get 
            {
                if (employees==null)
                {
                    employees = new ObservableCollection<Employee>();
                }
                return employees;
            }

        }
        
    }
}
View Code

 

主窗口的XAML头部引用名称空间:

xmlns:local="clr-namespace:TabControlDemo"

 

本例中TabControl控件中的TabItem用DataGrid控件来显示数据,

主窗口的资源中定义DataGridCell的样式资源:Key为dgCellStyle,使数据在单元格中居中显示:

 <Style x:Key="dgCellStyle" TargetType="{x:Type DataGridCell}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type DataGridCell}">
                        <Grid Background="{TemplateBinding Background}">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"></ContentPresenter>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
View Code

 

主窗口的资源中定义TabControl控件中的TabItem的样式:

 <DataTemplate DataType="{x:Type local:Department}">
            <Grid>
                <DataGrid ItemsSource="{Binding Path=Employees}"   AutoGenerateColumns="False" GridLinesVisibility="All"    SelectionMode="Single" IsReadOnly="True" CanUserAddRows="False" CanUserDeleteRows="False">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="姓名" Binding="{Binding Path=EmployeeName}" CellStyle="{StaticResource ResourceKey=dgCellStyle}" />
                        <DataGridTextColumn Header="性别" Binding="{Binding Sex}" CellStyle="{StaticResource ResourceKey=dgCellStyle}" />
                        <DataGridTextColumn Header="年龄" Binding="{Binding Age}" CellStyle="{StaticResource ResourceKey=dgCellStyle}" />
                        <DataGridTextColumn Header="职位" Binding="{Binding Title}" CellStyle="{StaticResource ResourceKey=dgCellStyle}"/>
                    </DataGrid.Columns>
                </DataGrid>
            </Grid>
        </DataTemplate>
View Code

 

主窗口的XAML完整代码:

<Window x:Class="TabControlDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:TabControlDemo"
        Title="MainWindow" Height="350" Width="525" DataContext="{Binding RelativeSource={RelativeSource Self}}" Loaded="Window_Loaded">
    <Window.Resources>
        <Style x:Key="dgCellStyle" TargetType="{x:Type DataGridCell}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type DataGridCell}">
                        <Grid Background="{TemplateBinding Background}">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"></ContentPresenter>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

        <DataTemplate DataType="{x:Type local:Department}">
            <Grid>
                <DataGrid ItemsSource="{Binding Path=Employees}"   AutoGenerateColumns="False" GridLinesVisibility="All"    SelectionMode="Single" IsReadOnly="True" CanUserAddRows="False" CanUserDeleteRows="False">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="姓名" Binding="{Binding Path=EmployeeName}" CellStyle="{StaticResource ResourceKey=dgCellStyle}" />
                        <DataGridTextColumn Header="性别" Binding="{Binding Sex}" CellStyle="{StaticResource ResourceKey=dgCellStyle}" />
                        <DataGridTextColumn Header="年龄" Binding="{Binding Age}" CellStyle="{StaticResource ResourceKey=dgCellStyle}" />
                        <DataGridTextColumn Header="职位" Binding="{Binding Title}" CellStyle="{StaticResource ResourceKey=dgCellStyle}"/>
                    </DataGrid.Columns>
                </DataGrid>
            </Grid>
        </DataTemplate>
    </Window.Resources>
    <Grid Margin="5">
        <TabControl ItemsSource="{Binding Path=Departments}">
            <TabControl.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}"/>
                </DataTemplate>
            </TabControl.ItemTemplate>
        </TabControl>
    </Grid>
</Window>
View Code

 

C#代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Collections.ObjectModel;

namespace TabControlDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window,INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        private ObservableCollection<Department> departments;

        public ObservableCollection<Department> Departments
        {
            get
            {
                if (departments == null)
                {
                    departments = new ObservableCollection<Department>();
                }
                return departments;
            }

        }

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Department d1 = new Department { Name="IT部"};
            d1.Employees.Add(new Employee() { EmployeeName="张三",Sex="",Age=30,Title="IT部部门经理"});
            d1.Employees.Add(new Employee() { EmployeeName = "李四", Sex = "", Age = 28, Title = "高级工程师" });
            d1.Employees.Add(new Employee() { EmployeeName = "王五", Sex = "", Age =23, Title = "软件工程师" });
            d1.Employees.Add(new Employee() { EmployeeName = "小丽", Sex = "", Age = 19, Title = "助理工程师" });

            Department d2 = new Department { Name = "采购部" };
            d2.Employees.Add(new Employee() { EmployeeName = "孙钱", Sex = "", Age = 30, Title = "采购部部门经理" });
            d2.Employees.Add(new Employee() { EmployeeName = "胡言", Sex = "", Age = 28, Title = "采购员" });
            d2.Employees.Add(new Employee() { EmployeeName = "梁雨", Sex = "", Age = 23, Title = "采购员" });

            Department d3 = new Department { Name = "销售部" };
            d3.Employees.Add(new Employee() { EmployeeName = "刘明", Sex = "", Age = 30, Title = "销售部部门经理" });
            d3.Employees.Add(new Employee() { EmployeeName = "霍奇", Sex = "", Age = 28, Title = "销售员" });
            d3.Employees.Add(new Employee() { EmployeeName = "何军", Sex = "", Age = 23, Title = "销售员" });

            this.Departments.Add(d1);
            this.Departments.Add(d2);
            this.Departments.Add(d3);
        }

      
    }
}
View Code

 

 

运行效果:

 

 

转载于:https://www.cnblogs.com/527289276qq/p/5329181.html

### C# WPFTabControl 控件与用户控件绑定的方法 在 C# WPF 开发中,`TabControl` 是一种常用的标签页容器控件,用于分组显示多个子页面或视图。为了实现 `TabControl` 和用户控件之间的动态绑定,可以利用数据绑定机制以及 MVVM 设计模式来完成这一需求。 以下是具体方法和示例代码: #### 数据模型定义 创建一个简单的数据模型类,用于存储每个选项卡的标题及其对应的用户控件实例。 ```csharp public class TabItemViewModel { public string Header { get; set; } public object Content { get; set; } // 可以是任何类型的对象,通常是一个用户控件 } ``` #### 主窗口 ViewModel 定义 通过集合属性保存所有的选项卡项,并提供给 UI 进行绑定。 ```csharp using System.Collections.ObjectModel; public class MainWindowViewModel { public ObservableCollection<TabItemViewModel> Tabs { get; set; } public MainWindowViewModel() { Tabs = new ObservableCollection<TabItemViewModel> { new TabItemViewModel { Header = "Tab 1", Content = new UserControl1() }, new TabItemViewModel { Header = "Tab 2", Content = new UserControl2() }, new TabItemViewModel { Header = "Tab 3", Content = new UserControl3() } }; } } ``` #### XAML 配置 在 XAML 文件中配置 `TabControl` 的数据模板,使其能够正确渲染每个选项卡的内容。 ```xml <Window.DataContext> <local:MainWindowViewModel /> </Window.DataContext> <TabControl ItemsSource="{Binding Tabs}"> <TabControl.ItemTemplate> <!-- 设置选项卡头部 --> <DataTemplate> <TextBlock Text="{Binding Header}" /> </DataTemplate> </TabControl.ItemTemplate> <TabControl.ContentTemplate> <!-- 设置选项卡内容 --> <DataTemplate> <ContentControl Content="{Binding Content}" /> </DataTemplate> </TabControl.ContentTemplate> </TabControl> ``` 上述代码实现了以下功能: - 使用 `ItemsSource` 属性将 `TabControl` 绑定到 ViewModel 中的 `Tabs` 集合。 - 利用 `ItemTemplate` 自定义选项卡头部分的外观。 - 借助 `ContentTemplate` 动态加载并呈现每个选项卡对应的内容区域[^1]。 此方式不仅支持静态绑定预定义的用户控件,还允许运行时动态添加新的选项卡及关联逻辑[^3]。 #### 注意事项 当处理复杂场景下的性能优化时,需注意避免不必要的资源消耗。例如,在切换不同标签页时不重新初始化已存在的用户控件实例;或者对于某些不常访问的大规模界面组件考虑延迟加载策略等技术手段加以改进[^2]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值