为什么在TabControl selectionchanged事件期间添加行时数据网格被锁定?

时间:2016-07-11 12:30:53

标签: c# wpf datagrid tabcontrol selectionchanged

非常简单的设置: 将数据网格放在TabItem中(来自TabControl)。在TabControl的SelectionChanged-Event期间添加内容,具体取决于新的SelectedIndex。 如果数据网格位于选定的选项卡中,则数据网格将被锁定。它看起来不是只读或禁用,但你仍然无法编辑它。如果使用SelectIndex在选项卡外部的数据网格中添加一行,一切正常。

MainWindow.xaml

<Window x:Class="WpfApplication2.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:WpfApplication2"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <TabControl SelectionChanged="TabControl_SelectionChanged">
        <TabItem Header="Tab1">
        </TabItem>
        <TabItem Header="Tab2">
            <DataGrid Name="grdTexte2" AutoGenerateColumns="False" CanUserAddRows="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Binding="{Binding [TEXTID]}" Header="ID" Width="50"/>
                    <DataGridTextColumn Binding="{Binding [TEXT]}" Header="Text"/>
                </DataGrid.Columns>
            </DataGrid>
        </TabItem>
        <TabItem Header="Tab3">
            <DataGrid Name="grdTexte3" AutoGenerateColumns="False" CanUserAddRows="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Binding="{Binding [TEXTID]}" Header="ID" Width="50"/>
                    <DataGridTextColumn Binding="{Binding [TEXT]}" Header="Text"/>
                </DataGrid.Columns>
            </DataGrid>
        </TabItem>
    </TabControl>

</Grid>

MainWindow.xaml.cs

using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace WpfApplication2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!(sender is TabControl))
                return;
            TabControl control = (sender as TabControl);
            if (control.SelectedIndex == 1)
            {
                List<object> rows = new List<object>();
                Dictionary<string, object> columns = new Dictionary<string, object>();
                columns["TEXTID"] = "id";
                columns["TEXT"] = "TEXT";

                rows.Add(columns);
                grdTexte2.ItemsSource = rows;
                grdTexte3.ItemsSource = rows;
            }
        }
    }
}

0 个答案:

没有答案