You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF中UserControl与MainVM交互:实现数据添加至DataGrid

WPF实现从UserControl输入添加数据到主窗口DataGrid

要实现这个需求,核心是让两个UserControl与主窗口解耦通信,同时将输入数据绑定到DataGrid。以下是具体实现步骤:

1. 定义数据模型类

创建存储输入数据的实体类,作为DataGrid的数据源项:

public class DetailItem
{
    public string Name { get; set; }
    public string Description { get; set; }
    public bool IsActive { get; set; }
}

2. 修改输入控件(第二个UserControl)

为输入控件添加公开属性,方便主窗口获取输入值,同时添加重置输入的方法:

// InputUC.xaml.cs
public string Name => txtName.Text;
public string Description => txtDesc.Text;
public bool IsActive => chkIsActive.IsChecked ?? false;

// 重置输入框内容
public void ResetInput()
{
    txtName.Clear();
    txtDesc.Clear();
    chkIsActive.IsChecked = false;
}

3. 修改按钮控件(第一个UserControl)

为按钮控件定义点击事件,让主窗口可以订阅该事件响应操作:

// ButtonUC.xaml.cs
public event EventHandler AddButtonClicked;

private void btnAddDetails_Click(object sender, RoutedEventArgs e)
{
    // 触发事件通知主窗口
    AddButtonClicked?.Invoke(this, EventArgs.Empty);
}

4. 配置主窗口

主窗口XAML布局

在主窗口中引入两个UserControl,并配置DataGrid的列绑定:

<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApp"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        
        <!-- 按钮控件 -->
        <local:ButtonUC x:Name="buttonUC" Grid.Row="0" Margin="10"/>
        
        <!-- 输入控件 -->
        <local:InputUC x:Name="inputUC" Grid.Row="1" Margin="10"/>
        
        <!-- 数据表格 -->
        <DataGrid x:Name="dataGrid" Grid.Row="2" Margin="10" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="名称" Binding="{Binding Name}"/>
                <DataGridTextColumn Header="描述" Binding="{Binding Description}"/>
                <DataGridCheckBoxColumn Header="是否激活" Binding="{Binding IsActive}"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

主窗口后台逻辑

使用ObservableCollection作为DataGrid的数据源(集合变化时自动更新UI),并订阅按钮控件的点击事件,在事件中获取输入数据并添加到集合:

// MainWindow.xaml.cs
using System.Collections.ObjectModel;
using System.Windows;

namespace WpfApp
{
    public partial class MainWindow : Window
    {
        private readonly ObservableCollection<DetailItem> _detailItems = new ObservableCollection<DetailItem>();

        public MainWindow()
        {
            InitializeComponent();
            dataGrid.ItemsSource = _detailItems;
            // 订阅按钮点击事件
            buttonUC.AddButtonClicked += OnAddButtonClicked;
        }

        private void OnAddButtonClicked(object sender, EventArgs e)
        {
            // 构建新的数据项
            var newItem = new DetailItem
            {
                Name = inputUC.Name,
                Description = inputUC.Description,
                IsActive = inputUC.IsActive
            };
            
            // 添加到数据源集合
            _detailItems.Add(newItem);
            
            // 重置输入框
            inputUC.ResetInput();
        }
    }
}

实现说明

  • 通过事件通知让按钮控件与主窗口通信,避免两个UserControl直接耦合,符合WPF解耦设计原则。
  • 使用ObservableCollection作为数据源,确保集合数据变化时DataGrid自动刷新UI。
  • 输入控件通过公开属性让主窗口获取数据,无需暴露内部控件,保证封装性。

内容的提问来源于stack exchange,提问作者S.Nieshant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 13:13:14