首页 > 解决方案 > 选中时复选框列未更新

问题描述

这是代码:

xml:

<UserControl x:Class="Prototype.Forms.UserForm"
             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:Prototype.Forms"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="400">
    <Grid>
        <DataGrid Name="MainGrid">
        </DataGrid>
    </Grid>
</UserControl>

C#:

public partial class UserForm : UserControl
    {

        public UserForm(IList <Element> list)
        {
            InitializeComponent();

            DataTable dt = new DataTable();

            dt.Columns.Add(" ",typeof(bool));
            dt.Columns.Add("Iteration");
            dt.Columns.Add("View name");
            dt.Columns.Add("Type");

            for (int i = 0; i < list.Count; i++)
            {
                DataRow r = dt.NewRow();

                r[1] = i.ToString();
                r[2] = list[i].Name;
                r[3] = "some element type";

                dt.Rows.Add(r);
            }

            MainGrid.ItemsSource = dt.DefaultView;
            MainGrid.MouseLeftButtonUp += new MouseButtonEventHandler(CellClick);
        }

        private void CellClick(object sender, EventArgs e)
        {
            //Do stuff
        }
    }

所以我遇到的问题是我似乎无法检查多个复选框。一旦我尝试选中第二个复选框,之前选中的复选框就会变为未选中状态。

鼠标按钮事件是尝试使复选框保持选中状态但失败的尝试失败。

标签: c#wpfcheckboxdatagrid

解决方案


删除空格或为复选框列添加列名:

dt.Columns.Add("ColumnName", typeof(bool));

如果为名称传入 null 或空字符串 (""),则会为列指定默认名称(“Column1”、“Column2”等)。微软文档

将空格作为列名似乎存在问题。


推荐阅读