WPF DataGrid使用 自动显示行号、全选、三级联动、拖拽
1.DataGrid的使用自动显示行号(修复删除行时行号显示不正确)
dgTool.LoadingRow += new EventHandler<DataGridRowEventArgs>(dgTool_LoadingRow);
dgTool.UnloadingRow +=new EventHandler<DataGridRowEventArgs>(dgTool_UnloadingRow); void dgTool_LoadingRow(object sender, DataGridRowEventArgs e)
{
e.Row.Header = e.Row.GetIndex() + 1;
} void dgTool_UnloadingRow(object sender, DataGridRowEventArgs e)
{
dgTool_LoadingRow(sender, e);
if (dgTool.Items != null)
{
for (int i = 0; i < dgTool.Items.Count; i++)
{
try
{
DataGridRow row = dgTool.ItemContainerGenerator.ContainerFromIndex(i) as DataGridRow;
if (row != null)
{
row.Header = (i + 1).ToString();
}
}
catch { }
}
} }
2.DataGrid新建一行,并为需要的单元格提供默认值
dgTool.InitializingNewItem += new InitializingNewItemEventHandler(dgTool_InitializingNewItem);
dgTool.RowEditEnding += new EventHandler<DataGridRowEditEndingEventArgs>(dgTool_RowEditEnding); private void dgTool_InitializingNewItem(object sender, InitializingNewItemEventArgs e)
{
//这里的实体为你绑定数据源中的实体类型
EntityType newItem = e.NewItem as EntityType;
newItem.ID = dgTool.Items.Count - 2;
}
//这里是为了解决添加完成一行数据之后,行号显示不正确(当然还可以做其他操作)
void dgTool_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
if (dgTool.Items != null)
{
for (int i = 0; i < dgTool.Items.Count; i++)
{ try
{
DataGridRow row = dgTool.ItemContainerGenerator.ContainerFromIndex(i) as DataGridRow;
if (row != null)
{
row.Header = (i + 1).ToString();
}
}
catch { }
}
}
}
3.DataGrid实现全选和单选
1)DataGrid绑定数据实体类Entity
public class Entity : INotifyPropertyChanged
{ //标记是否删除
private bool isChecked = false;
public bool IsChecked
{
get
{
return isChecked;
}
set
{
isChecked = value;
NotifyPropertyChanged("IsChecked");
}
} //序号
private int id = 0;
public int ID
{
get { return id; }
set
{
id = value;
NotifyPropertyChanged("ID");
}
} public event PropertyChangedEventHandler PropertyChanged; public void NotifyPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
} }
2)前台界面XAML
<DataGrid x:Name="dgTool" Grid.Row="2" SelectionChanged="dgTool_SelectionChanged" RowHeaderWidth="50" FontFamily="Microsoft YaHei" FontSize="16" FontWeight="Normal" SelectionMode="Single" AutoGenerateColumns="False" CanUserAddRows="True" CanUserDeleteRows="True" IsReadOnly="False" CanUserSortColumns="False" AlternatingRowBackground="LightGray">
<DataGrid.ColumnHeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="HorizontalContentAlignment" Value="Center">
</Setter>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.Header>
<CheckBox Name="selectAll_checkBox" Content="全选" IsThreeState="True" HorizontalAlignment="Center" Click="selectAll_checkBox_Click" />
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox Name="select_checkBox" IsChecked="{Binding Path=IsChecked}" Click="select_checkBox_Click"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="ID" Width="*" Binding="{Binding Path=ID}"/>
</DataGrid.Columns> </DataGrid>
3)后台事件
int count = 0;
private void select_checkBox_Click(object sender, RoutedEventArgs e)
{
//因为我前台做的是单项绑定,所有要手动修改数据源IsChecked属性,因为我要统计勾选的个数
//做成双向绑定的话(将IsChecked="{Binding Path=IsChecked}" 改成 IsChecked="{Binding Path=IsChecked,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"即可),就不需要手动修改IsChecked属性了,但还是要统计个数
var item = dgTool.SelectedItem;
if (item != null)
{
Entity entity = item as Entity;
if (entity == null) return;
if ((bool)((System.Windows.Controls.Primitives.ToggleButton)(sender)).IsChecked)
{
entity.IsChecked = true;
count++;
}
else
{
entity.IsChecked = false;
count--;
}
//根据勾选的个数,改变列头的状态 全选、全不选、部分选
CheckBox cb = this.FindName("selectAll_checkBox") as CheckBox;
cb.IsThreeState = true;
if (cb != null)
{
if (count == 0) cb.IsChecked = false;
List<Entity> source = dgTool.ItemsSource as List<Entity>;
if (source != null)
{
if (count == source.Count) cb.IsChecked = true;
else cb.IsChecked = null; }
} }
} private void selectAll_checkBox_Click(object sender, RoutedEventArgs e)
{
List<Entity> source = dgTool.ItemsSource as List<Entity>;
if (source == null) return;
bool? isThreeStatus = ((System.Windows.Controls.Primitives.ToggleButton)(sender)).IsChecked;
if (isThreeStatus == null) return;
if ((bool)isThreeStatus)
{
foreach (Entity each in source)
{
each.IsChecked = true;
}
count = source.Count;
}
else
{
foreach (Entity each in source)
{
each.IsChecked = false;
}
count = 0;
} }
4)删除按钮事件
//删除按钮事件
private void btnDelRows_Click(object sender, RoutedEventArgs e)
{
List<Entity> source = dgTool.ItemsSource as List<Entity>;
if (source == null) return;
int count = 0;
for (int i = 0; i < source.Count; i++)
{
Entity temp = source[i];
if (temp.IsChecked)
{
source.Remove(temp); //因为删除导致后面的项成为当前项
i--; //所有索引应该不变,由于后面i会加1,先减一
count++;
}
}
if (count == 0) MessageBox.Show("请选择要删除的行");
else
{
MessageBox.Show("共删除" + count + "条记录");
}
dgTool.Items.Refresh(); //对DataGrid刷新数据 如果DataGrid中添加了排序则只能用下面的进行刷新
ICollectionView dataView = CollectionViewSource.GetDefaultView(dgTool.ItemsSource);
dataView.SortDescriptions.Add(new SortDescription("ID", ListSortDirection.Ascending));
dataView.Refresh();
}
4.三级联动
1)业务实体
public class Entity : INotifyPropertyChanged
{ //标记是否删除
private bool isChecked = false;
public bool IsChecked
{
get
{
return isChecked;
}
set
{
isChecked = value;
NotifyPropertyChanged("IsChecked");
}
} //序号
private int id = 0;
public int ID
{
get { return id; }
set
{
id = value;
NotifyPropertyChanged("ID");
}
}
//省
private int provinceNo = 0;
public int ProvinceNo
{
get { return provinceNo; }
set
{
provinceNo = value;
NotifyPropertyChanged("ProvinceNo");
}
}
private string provinceName = string.Empty;
public string ProvinceName
{
get { return provinceName; }
set
{
provinceName = value;
NotifyPropertyChanged("ProvinceName");
}
} //市
private int cityNo = 0;
public int CityNo
{
get { return cityNo; }
set
{
cityNo = value;
NotifyPropertyChanged("CityNo");
}
}
private string cityName = string.Empty;
public string CityName
{
get { return cityName; }
set
{
cityName = value;
NotifyPropertyChanged("CityName");
}
} //县
private int countyNo = 0;
public int CountyNo
{
get { return countyNo; }
set
{
countyNo = value;
NotifyPropertyChanged("CountyNo");
}
}
private string countyName = string.Empty;
public string CountyName
{
get { return countyName; }
set
{
countyName = value;
NotifyPropertyChanged("CountyName");
}
} public event PropertyChangedEventHandler PropertyChanged; public void NotifyPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
} }
2)前台界面
<DataGrid x:Name="dgTool" Grid.Row="2" SelectionChanged="dgTool_SelectionChanged" RowHeaderWidth="50" FontFamily="Microsoft YaHei" FontSize="16" FontWeight="Normal" SelectionMode="Single" AutoGenerateColumns="False" CanUserAddRows="True" CanUserDeleteRows="True" IsReadOnly="False" CanUserSortColumns="False" AlternatingRowBackground="LightGray" >
<DataGrid.ColumnHeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="HorizontalContentAlignment" Value="Center">
</Setter>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.Header>
<CheckBox Name="selectAll_checkBox" Content="全选" IsThreeState="True" HorizontalAlignment="Center" Click="selectAll_checkBox_Click" />
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox Name="select_checkBox" IsChecked="{Binding Path=IsChecked,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Click="select_checkBox_Click"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="ID" Width="*" Binding="{Binding Path=ID}"/>
<!--<DataGridComboBoxColumn x:Name="cbbProvinceName" Header="省" Width="*" TextBinding="{Binding Path=ProvinceName}" />-->
<DataGridTemplateColumn Header="省" Width="*">
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox x:Name="cbbProvinceName" Text="{Binding Path=ProvinceName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" IsSynchronizedWithCurrentItem="False" Loaded="cbbProvinceName_Loaded" SelectionChanged="cbbProvinceName_SelectionChanged" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate >
<TextBlock Text="{Binding Path=ProvinceName, Mode=OneWay}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="市" Width="*">
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox x:Name="cbbCityName" Text="{Binding Path=CityName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" IsSynchronizedWithCurrentItem="False" Loaded="cbbCityName_Loaded" SelectionChanged="cbbCityName_SelectionChanged">
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate >
<TextBlock Text="{Binding Path=CityName, Mode=OneWay}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn> <DataGridTemplateColumn Header="县" Width="*">
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox x:Name="cbbCountyName" Text="{Binding Path=CountyName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" IsSynchronizedWithCurrentItem="False" Loaded="cbbCountyName_Loaded" SelectionChanged="cbbCountyName_SelectionChanged" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate >
<TextBlock Text="{Binding Path=CountyName}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns> </DataGrid>
3)后台逻辑
int rowIndex = -1;
private void dgTool_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
rowIndex = ((System.Windows.Controls.DataGrid)((sender))).SelectedIndex;
}
处理省逻辑
private void cbbProvinceName_Loaded(object sender, RoutedEventArgs e)
{
var cbbProvinceNam = sender as ComboBox;
cbbProvinceNam.ItemsSource = provinceSource;
cbbProvinceNam.SelectedValuePath = "ProvinceNo";
cbbProvinceNam.DisplayMemberPath = "ProvinceName";
} private void cbbProvinceName_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var cbbProvinceName = sender as ComboBox;
var rowData = source.ElementAt(rowIndex);
if (cbbProvinceName != null && cbbProvinceName.SelectedValue != null)
{
rowData.ProvinceNo = int.Parse(cbbProvinceName.SelectedValue.ToString());
} rowData.CityNo = -1;
rowData.CityName = string.Empty;
rowData.CountyNo = -1;
rowData.CountyName = string.Empty;
}
处理市逻辑
private void cbbCityName_Loaded(object sender, RoutedEventArgs e)
{
var cbbCityName = sender as ComboBox;
var rowData = source.ElementAt(rowIndex);
if (rowData != null)
{
if (String.IsNullOrEmpty(rowData.ProvinceName))
{
MessageBox.Show("请先选择省");
e.Handled = true;
return;
}
else
{
cbbCityName.ItemsSource = citySource;
cbbCityName.SelectedValuePath = "CityNo";
cbbCityName.DisplayMemberPath = "CityName";
}
}
} private void cbbCityName_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var rowData = source.ElementAt(rowIndex);
rowData.CountyName = string.Empty;
rowData.CountyNo = -1;
}
处理县逻辑
private void cbbCountyName_Loaded(object sender, RoutedEventArgs e)
{
var cbbCountyName = sender as ComboBox;
var rowData = source.ElementAt(rowIndex);
if (rowData != null)
{
e.Handled = true;
return;
}
if (String.IsNullOrEmpty(rowData.ProvinceName))
{
MessageBox.Show("请先选择省");
e.Handled = true;
return;
}
else
{
if (string.IsNullOrEmpty(rowData.CityName))
{
MessageBox.Show("请先选择市");
e.Handled = true;
return;
}
else
{ cbbCountyName.ItemsSource = countySource;
cbbCountyName.DisplayMemberPath = "CountyName";
cbbCountyName.SelectedValuePath = "CountyNo"; }
}
} private void cbbCountyName_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var cbbCountyName = sender as ComboBox;
var rowData = source.ElementAt(rowIndex);
if (cbbCountyName != null && cbbCountyName.SelectedValue != null)
rowData.CountyNo = int.Parse(cbbCountyName.SelectedValue.ToString());
}
WPF DataGrid使用 自动显示行号、全选、三级联动、拖拽的更多相关文章
- winedt设置自动显示行号[latex]
options--preferences--appearance 在show line numbers for modes下面的文本框里添加;Tex 这样新建或者打开tex文件的时候就自动显示行号了( ...
- vim显示行号、语法高亮、自动缩进的设置
转载自:http://blog.csdn.net/chuanj1985/article/details/6873830 在UBUNTU中vim的配置文件存放在/etc/vim目录中,配置文件名为v ...
- Ubuntu vim显示行号语法高亮自动缩进
配置文件名为Ubuntu vimrc在Fedora中vim的配置文件存放在/etc目录中,配置文件名为Ubuntu vimrc在终端 输入以下命令来编辑Ubuntu vimrc配置文件:sudo vi ...
- linux系统下Vi编辑器或者Vim编辑器设置显示行号、自动缩进、调整tab键宽度的技巧?
工作中嫌vim 中一个tab键的宽度太大,linux系统默认,没改之前是一个tab键宽度是8个字符,想改成4个字符, 操作如下:(注意:这是在root用户下)cd ~vim .vimrc添加如下几行: ...
- Easyui Datagrid 修改显示行号列宽度
EasyUI中Datagrid的第一列显示行号,可是如果数据量大的的时候,显示行号的那一列数据会显示不完全的. 可以通过修改Datagrid的样式来解决这个问题,在样式中加入下面这个样式,就可以自己修 ...
- vim显示行号、语法高亮、自动缩进、添加下划线的设置
ubuntu默认是没有安装vim的,所以设置以前请先安装vim:sudo apt-get install vim. 然后 打开vim的配置文件:sudo vim /etc/vim/vimrc 或者 s ...
- vim 设置TAB宽度、显示行号、自动缩进、自动换行宽度
一.vim ~/.vimrc 二.添加如下几行:(括号中的不是,是我添加的) set shiftwidth=4 (表示每一级缩进的长度)set softtabstop=4 ...
- Ubuntu18.04系统下安装Pycharm&vim设置自动缩进及默认显示行号
Ubuntu18.04系统自带python3.6及python2.7,Pycharm是一款非常强大的IDE.目前Pycharm有两个版本:专业版和Community社区,区别是专业版是收费,而且功能更 ...
- linux vim 配置文件(高亮+自动缩进+行号+折叠+优化)
点评:将一下代码copy到 用户目录下 新建文件为 .vimrc保存即可生效 如果想所有用户生效 请修改 /etc/vimrc (建议先cp一份)"===================== ...
- vim 配置文件 ,高亮+自动缩进+行号+折叠+优化
vim 配置文件 ,高亮+自动缩进+行号+折叠+优化 将一下代码copy到 用户目录下 新建文件为 .vimrc保存即可生效: 如果想所有用户生效 请修改 /etc/vimrc (建议先cp一份)& ...
随机推荐
- github仓库开始启用Token认证,用户名密码模式将在2021年8月停止使用
提交代码到github原本使用github的登录账号和密码即可.现在github出于安全的考虑,将在2021年8月停止使用账号和密码的方式访问github仓库,改为token认证的方式. 创建步骤 点 ...
- HarmonyOS课程尝鲜计划,优享特权大礼包
报名入口:https://developer.huawei.com/consumer/cn/activity/901689042385499023
- redis 简单整理——哨兵原理[三十一]
前言 简单介绍一下哨兵的原理. 正文 一套合理的监控机制是Sentinel节点判定节点不可达的重要保证,Redis Sentinel通过三个定时监控任务完成对各个节点发现和监控: 1)每隔10秒,每个 ...
- redis 简单整理——哨兵部署业务图[二十九]
前言 简单介绍一下哨兵的部署业务图,非部署步骤. 正文 看一下部署的拓扑图: 然后这里用docker 来部署一下哨兵模式. 搭建一主二从. version: '3.7' services: maste ...
- Flutter开发技巧集锦
flutter中单例的写法 class AccountManager { factory AccountManager() => _instance ??= AccountManager._() ...
- Oracle 简单的创建一个定时任务job
Oracle 简单的创建一个定时任务job Oracle 简单的创建一个定时任务job 没有什么前置步骤,无非就是把存储过程或者SQL提前写好,就不说了,直接执行一下下面的语句即可创建一个job de ...
- 教你如何进行Prometheus 分片自动缩放
本文分享自华为云社区<使用 Prometheus-Operator 进行 Prometheus + Keda 分片自动缩放>,作者: Kubeservice@董江. 垂直缩放与水平缩放 P ...
- 基于IoT全链路实时质量-魔洛哥
简介: 通过基于IoT的全链路实时质量,业务使用狄仁杰进行全链路埋点后,可一键接入魔洛哥平台,实现终端问题的实时感知和链路分析,以及智能终端系统业务场景的全链路实时质量.整体方案接入成本低(分钟级别接 ...
- Dubbo-go 服务代理模型
简介:HSF 是阿里集团 RPC/服务治理 领域的标杆,Go 语言又因为其高并发,云原生的特性,拥有广阔的发展前景和实践场景,服务代理模型只是一种落地场景,除此之外,还有更多的应用场景值得我们在研发 ...
- 什么是好的错误消息? 讨论一下Java系统中的错误码设计
简介:一个好的Error Message主要包含三个部分:Context: 什么导致了错误?发生错误的时候代码想做什么?The error itself: 到底是什么导致了失败?具体的原因和当时的数据 ...