WPF DataGrid 使用

 

1、举例

 

<Window x:Class="WpfApplication1.com.view.DataGridWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DataGridWindow" Height="300" Width="500">
    <Grid>
        
        <DataGrid Name="datagrid1" AutoGenerateColumns="True"/>
        
        <StackPanel HorizontalAlignment="Right" VerticalAlignment="Top">
            <Button Name="btnShowData" Content="显示数据" Click="btnShowData_Click"/>
        </StackPanel>
    </Grid>
</Window>

 

namespace WpfApplication1.com.view
{
    /// <summary>
    /// DataGridWindow.xaml 的交互逻辑
    /// </summary>
    public partial class DataGridWindow : Window
    {
        private List<StudentData> studentDatas = new List<StudentData>();
        public DataGridWindow()
        {
            InitializeComponent();


            for(int i=1;i<=5;i++)
            {
                StudentData stuData = new StudentData();
                stuData.studentID = 100 + i;
                stuData.studentName = "姓名" + i;
                studentDatas.Add(stuData);
            }
        }

        private void btnShowData_Click(object sender, RoutedEventArgs e)
        {
            datagrid1.ItemsSource = studentDatas;
        }
    }
}

 

 

namespace WpfApplication1.com.Data
{
    public class StudentData : BindableObject
    {
        public int studentID = 0;
        public string studentName = "";

        public int StudentID
        {
            get { return studentID; }
            set { SetProperty<int>(ref studentID, value); }
        }

        public string StudentName
        {
            get { return studentName; }
            set { SetProperty<string>(ref studentName, value); }
        }
    }
}

 

namespace WpfApplication1.com.Data
{
    public abstract class BindableObject : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        protected void SetProperty<T>(ref T item, T value, [CallerMemberName] string propertyName = null)
        {
            if (!EqualityComparer<T>.Default.Equals(item, value))
            {
                item = value;
                OnPropertyChanged(propertyName);
            }
        }
    } 
}

 

以上是一个最简单的例子:

AutoGenerateColumns属性:是否自动创建列(默认为true)

CanUserAddRows属性:是否可以添加新行

需要注意的是数据源,这个具体如何提供数据方式很多种,需要绑定,并时时更新需要实现INotifyPropertyChanged接口

 

2、举例

 

<Window x:Class="WpfApplication1.com.view.DataGridWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DataGridWindow" Height="300" Width="500">
    <Grid>
        
        <DataGrid Name="datagrid1" AutoGenerateColumns="True" Visibility="Hidden"/>
        
        <DataGrid Name="datagrid2" AutoGenerateColumns="False" CanUserAddRows="False">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding StudentID}" Header="学号"/>
                <DataGridTextColumn Binding="{Binding StudentName}" Header="姓名"/>
            </DataGrid.Columns>
        </DataGrid>
        
        
        
        <StackPanel HorizontalAlignment="Right" VerticalAlignment="Top">
            <Button Name="btnShowData" Content="显示数据" Click="btnShowData_Click"/>
        </StackPanel>
    </Grid>
</Window>


这个datagrid2是指定了显示哪些数据,并设置了列标题

 

 CanUserAddRow属性:是否可以添加新行(默认为True),从例1效果图看看到每次生成的表格最下面都会有一个空白行,如果设置为false,则不会显示空白行

 

3、关于DataGrid的列的呈现方式

(1)DataGridTextColumn 文本

(2)DataGridCheckBoxColumn 复选框

(3)DataGridComboBoxColumn 下拉菜单

(4)DataGridHyperlinkColumn 超链接文本

(5)DataGridTemplateColumn 如果想自定义模板

 

3、举例

有一个表头有个复选框可以进行全选

数据类  

    public abstract class BindableObject : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        protected void SetProperty<T>(ref T item, T value, [CallerMemberName] string propertyName = null)
        {
            if (!EqualityComparer<T>.Default.Equals(item, value))
            {
                item = value;
                OnPropertyChanged(propertyName);
            }
        }
    } 

 

 

 

    public class Person : BindableObject
    {
        private string _name = "";
        private bool _isSelected = false;

        public string Name
        {
            get { return _name; }
            set { SetProperty<string>(ref _name, value); }
        }
        
        public bool IsSelected
        {
            get { return _isSelected; }
            set { SetProperty<bool>(ref _isSelected, value); }
        }
    }

 

前台XAML

 

需要注意<CheckBox IsChecked="{Binding IsSelected,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>进行了双向绑定

<Window x:Class="WpfApplication1.DataGridWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DataGridWindow" Height="500" Width="800">
    <Grid>
        
        <DataGrid Name="datagrid1" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.HeaderTemplate>
                        <DataTemplate>
                            <CheckBox x:Name="checkAll" Click="checkAll_Click"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.HeaderTemplate>
                    
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox IsChecked="{Binding IsSelected,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                
                <DataGridTextColumn Binding="{Binding Name}" Header="姓名"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

 

 

 

    public partial class DataGridWindow : Window
    {

        private List<Person> _personList = new List<Person>();

        public DataGridWindow()
        {
            InitializeComponent();

            _personList.Add(new Person { Name="小明"});
            _personList.Add(new Person { Name = "小红"});

            datagrid1.ItemsSource = _personList;
        }

        private void checkAll_Click(object sender, RoutedEventArgs e)
        {
            for(int i=0;i<_personList.Count;i++)
            {
                _personList[i].IsSelected = !_personList[i].IsSelected;
            }
        }
    }

 

 

行数据、列数据、单元数据获取方式

//获取行
int rowIndex = 0;
DataGridRow gridRow = (DataGridRow)datagrid1.ItemContainerGenerator.ContainerFromIndex(rowIndex);

//获取列
int columnIndex = 0;
DataGridColumn gridColumn = datagrid1.Columns[columnIndex];

//获取单元格数据
FrameworkElement element = gridColumn.GetCellContent(gridRow);

获取第一列的DataGridCheckBoxColumn方法

前台

            <DataGrid Name="datagrid1" AutoGenerateColumns="False" CanUserAddRows="False" Width="350" Height="200" LoadingRow="datagrid1_LoadingRow">
                <DataGrid.Columns>
                    <DataGridCheckBoxColumn/>

                    <DataGridTextColumn Binding="{Binding ScreenX}" Header="ScreenX"/>
                    <DataGridTextColumn Binding="{Binding ScreenY}" Header="ScreenY"/>
                    <DataGridTextColumn Binding="{Binding R}" Header="R"/>
                    <DataGridTextColumn Binding="{Binding G}" Header="G"/>
                    <DataGridTextColumn Binding="{Binding B}" Header="B"/>
                </DataGrid.Columns>
            </DataGrid>

后台

            //获取第1行第1列的这个就是DataGridCheckBoxColumn
            int rowIndex = 0;
            int columnIndex = 0;
            DataGridRow gridRow = (DataGridRow)datagrid1.ItemContainerGenerator.ContainerFromIndex(rowIndex);
            DataGridColumn gridColumn = datagrid1.Columns[columnIndex];
            FrameworkElement element = gridColumn.GetCellContent(gridRow);

            CheckBox checkBox = (System.Windows.Controls.CheckBox)element;//这个就是DataGridCheckBoxColumn

 

 

 

 

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值