DevExpress 技巧
LabelControl
居中显示
labelControl1.AutoSizeMode = DevExpress.XtraEditors.LabelAutoSizeMode.None;
labelControl1.Dock = DockStyle.Fill;
// 垂直居中
labelControl1.Appearance.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center;
// 水平居中
labelControl1.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
Html标签
labelControl1.AllowHtmlString = true;
labelControl1.Appearance.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
labelControl1.Text = "<size=18>Size=18<br>" +
"<b>Bold</b> <i>Italic</i> <u>Underline</u><br>" +
"<size=10>Size=10<br>" +
"<color=255,0,0>Sample Text</color></size>" +
"<href=www.devexpress.com>Hyperlink</href>";
TextEdit
蒙版提示
textEdit1.Properties.AllowNullInput = DevExpress.Utils.DefaultBoolean.True;
textEdit1.Properties.NullText = "请输入数据:";
textEdit1.Properties.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
textEdit1.Properties.Appearance.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center;
输入限定
// 限定数字
textEdit1.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
// 限定表达式
textEdit1.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;
textEdit1.Properties.Mask.EditMask = "[0-9]*";
MemoEdit
多行编辑
memoEdit1.Properties.ScrollBars = ScrollBars.Vertical;
memoEdit1.Properties.WordWrap = true;
memoEdit1.Properties.AllowMouseWheel = true;
memoEdit1.Properties.AcceptsReturn = true;
memoEdit1.Properties.AcceptsTab = false;
ListBoxControl
可选择的项目列表。
var listInfo = GetListInfo();
listBoxControl1.DataSource = listInfo;
listBoxControl1.DisplayMember = "PropertName1";
listBoxControl1.SelectedValueChanged += ListBoxControl1_SelectedValueChanged;
private void ListBoxControl1_SelectedValueChanged(object sender, EventArgs e) {
var listBoxControl = sender as ListBoxControl;
if (!listBoxControl.Focused) return;
XtraMessageBox.Show(listBoxControl.SelectedValue.ToString());
}
绑定模式会使listInfo的变化反应到控件显示,且listBoxControl1.Items是没有数据的,但不影响SelectedValueChanged等操作。
若listInfo是可通知的对象集合(BindingList
若是List
详情查看Winform 属性值绑定、转换、实时通知
CheckedListBoxControl
带选择框的 ListBoxControl。
public static void DataSourceBinding(this CheckedListBoxControl control, List<Source> dataSource)
{
// true 多列显示 控件高度不变
// false 默认单例显示 控件宽度不变,有垂直滚动条
control.MultiColumn = true;
// 多列显示时,列宽设置;默认宽为各项最长长度
control.ColumnWidth = 80;
// One,单选一项,再点可勾选
// MultiSimple, 可选多项,统一勾选
// MultiExtended, 类似 One, 可在选择框上任意勾选多项
control.SelectionMode = SelectionMode.One;
// true, 点击一项即可勾选
control.CheckOnClick = true;
// 绑定
control.DataSource = dataSource;
control.DisplayMember = "Value";
control.ValueMember = "Key";
}
checkedListBoxControl1.DataSourceBinding(list);
foreach (Source item in checkedListBoxControl1.CheckedItems)
{
// TODO
}
ComboBoxEdit
下拉列表。可绑定任意类型的项目集合,项目显示文本取决于类型的ToString()的内容。
var list= EnumExtends.GetEnumResource<EnumType>();
comboBoxEdit1.Properties.Items.AddRange(list);
// 文本不可编辑
comboBoxEdit1.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;
private void comboBoxEdit1_SelectedIndexChanged(object sender, EventArgs e)
{
if (sender is ComboBoxEdit cbe && cbe.SelectedItem is Source item)
{
labelControl1.Text = item.Key + " " + item.Value;
}
}
LookUpEdit
下拉列表,可查找,轻量级表格。
var dic = EnumExtends.EnumToDic<EnumType>();
lookUpEdit1.DataSourceBinding(dic);
lookUpEdit1.Properties.SearchMode = DevExpress.XtraEditors.Controls.SearchMode.AutoFilter;
lookUpEdit1.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
public static void DataSourceBinding(this LookUpEdit lookUpEdit, Dictionary<int,string> dataSource)
{
lookUpEdit.Properties.DataSource = dataSource;
lookUpEdit.Properties.ShowHeader = false;
lookUpEdit.Properties.ShowFooter = false;
lookUpEdit.Properties.ValueMember = "Key";
lookUpEdit.Properties.DisplayMember = "Value";
lookUpEdit.Properties.NullText = "请选择";
lookUpEdit.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Value"));
lookUpEdit.ItemIndex = -1;
lookUpEdit.Properties.SearchMode = DevExpress.XtraEditors.Controls.SearchMode.OnlyInPopup;
lookUpEdit.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
lookUpEdit.Properties.PopupSizeable = true;
lookUpEdit.Properties.BestFitMode = DevExpress.XtraEditors.Controls.BestFitMode.BestFitResizePopup;
lookUpEdit.Properties.BestFitWidth = 0;
lookUpEdit.Properties.BestFit();
lookUpEdit.Properties.PopupFormMinSize = new Size(10, 0);
//lookUpEdit.Properties.UseDropDownRowsAsMaxCount = true; v14.2
}
private void lookUpEdit1_EditValueChanged(object sender, EventArgs e)
{
if (sender is LookUpEdit lue && lue.GetSelectedDataRow() is KeyValuePair<int, string> pair)
{
labelControl1.Text = lue.EditValue + " " + pair.Value;
}
}
GridLookUpEdit
可展示二维表单的LookUpEdit。
单选响应,可多项勾选。
var list = EnumExtends.GetEnumResourceEx<EnumType>();
DataSourceBinding(gridLookUpEdit1, _listLightSourceDarkField);
gridLookUpEdit1.Properties.NullText = "初始化显示";
private void DataSourceBinding(GridLookUpEdit gridLookUpEdit, List<SourceSelected> dataSource)
{
// 数据绑定
gridLookUpEdit.Properties.DataSource = dataSource;
gridLookUpEdit.Properties.ValueMember = "Key";
gridLookUpEdit.Properties.DisplayMember = "Value";
gridLookUpEdit.Properties.NullText = "请选择";
gridLookUpEdit.Properties.ShowFooter = false;
gridLookUpEdit.Properties.View.OptionsBehavior.AutoPopulateColumns = false;
// 添加列
var column = new GridColumn() { FieldName = "Value" };
column.VisibleIndex = 0;
gridLookUpEdit.Properties.View.Columns.Add(column);
column = new GridColumn() { FieldName = "IsSelected" };
column.VisibleIndex = 1;
column.OptionsColumn.AllowEdit = true;
var ckb = new RepositoryItemCheckEdit();
column.ColumnEdit = ckb;
gridLookUpEdit.Properties.View.Columns.Add(column);
gridLookUpEdit.Properties.View.OptionsView.ShowColumnHeaders = false;// 隐藏行首
gridLookUpEdit.Properties.View.OptionsView.ShowIndicator = false; // 隐藏索引
// 不允许输入
gridLookUpEdit.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
// 模糊查询
//gridLookUpEdit.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
//gridLookUpEdit.Properties.AutoComplete = false;
//gridLookUpEdit.Properties.ImmediatePopup = true;
//gridLookUpEdit.Properties.PopupFilterMode = PopupFilterMode.Contains;
// 自由输入
//gridLookUpEdit.ProcessNewValue -= GridLookUpEdit_ProcessNewValue;
//gridLookUpEdit.ProcessNewValue += GridLookUpEdit_ProcessNewValue;
// 自适应各列
gridLookUpEdit.Properties.View.OptionsView.ColumnAutoWidth = true;
gridLookUpEdit.Properties.View.BestFitColumns();
gridLookUpEdit.Properties.BestFitMode = DevExpress.XtraEditors.Controls.BestFitMode.BestFit;
// 弹框大小
gridLookUpEdit.Properties.PopupSizeable = true;
gridLookUpEdit.Properties.PopupFormMinSize = new Size(10, 10);
gridLookUpEdit.Properties.PopupFormSize = new Size(100, 60);
}
private static void GridLookUpEdit_ProcessNewValue(object sender, DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs e)
{
if (!string.IsNullOrWhiteSpace(e.DisplayValue?.ToString()))
{
var edit = sender as GridLookUpEdit;
var dt = edit.Properties.DataSource as DataTable;
if (dt != null)
{
var dr = dt.NewRow();
dr[edit.Properties.DisplayMember] = e.DisplayValue;
dr[edit.Properties.ValueMember] = e.DisplayValue;
dt.Rows.Add(dr);
}
var list = edit.Properties.DataSource as List<Source>;
if (list != null)
{
list.Add(new SourceSelected() { Key = list.Count + 1, Value = e.DisplayValue?.ToString() });
}
}
e.Handled = true;
}
// 勾选标识
private bool _bCheckChanged;
private void GridLookUpEdit1_QueryCloseUp(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = _bCheckChanged; // 勾选时弹框不关闭
var control = (GridLookUpEdit)sender;
var list = gridLookUpEdit1View.DataSource as List<SourceSelected>;
}
private void GridLookUpEdit1View_MouseDown(object sender, MouseEventArgs e)
{
// 左键勾选
var view = (GridView)sender;
var hint = view.CalcHitInfo(e.X, e.Y);
if (view.RowCount == 0 || !hint.InRowCell || e.Button != MouseButtons.Left || e.Clicks != 1)
{
return;
}
_bCheckChanged = false;
// 响应勾选列
if (hint.Column.FieldName == "IsSelected")
{
_bCheckChanged = true;
view.FocusedRowHandle = -1;
var item = view.GetRow(hint.RowHandle) as SourceSelected;
if (item != null)
{
view.SetRowCellValue(hint.RowHandle, "IsSelected", !item.IsSelected);
}
}
}
LayoutControl
布局控件,跟随窗体变化大小,创建并维护控件的一致布局。
当SizeConStraintsType=Custom,控件Size由MinSize、MaxSize决定;
当SizeConstraintsType=SupportHorzAlignment,由ControlAlignment进行布局,且控件属性AutoSizeInLayoutControl=true;
已布局的控件,在后台不可动态调整。
DataLayoutControl
可绑定源字段的LayoutControl。与BindingSource结合使用。
GridControl
gridControl1.DataSource = demoList;
基本设置
// 内嵌导航页
gridControl1.UseEmbeddedNavigator = true;
gridControl1.EmbeddedNavigator.Buttons.PrevPage.Visible = true;
gridControl1.EmbeddedNavigator.Buttons.Prev.Visible = true;
gridControl1.EmbeddedNavigator.Buttons.NextPage.Visible = true;
gridControl1.EmbeddedNavigator.Buttons.Next.Visible = true;
gridControl1.EmbeddedNavigator.Buttons.Append.Visible = false;
gridControl1.EmbeddedNavigator.Buttons.CancelEdit.Visible = false;
gridControl1.EmbeddedNavigator.Buttons.Edit.Visible = false;
gridControl1.EmbeddedNavigator.Buttons.EndEdit.Visible = false;
gridControl1.EmbeddedNavigator.Buttons.Remove.Visible = false;
gridControl1.EmbeddedNavigator.TextStringFormat = "{0} / {1}";
// 禁用合计
gridView1.OptionsView.ShowFooter = false;
// 禁用自带的搜索功能
gridView1.OptionsFind.AlwaysVisible = false;
// 指定列的合计类型
//gridView1.Columns["列名"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
// 合计显示格式
//gridView1.Columns["列名"].SummaryItem.DisplayFormat = "{0:f2}";
// 禁用列头右键菜单
gridView1.OptionsMenu.EnableColumnMenu = false;
// 自适应各列
gridView1.OptionsView.ColumnAutoWidth = true;
// 隐藏主面板
gridView1.OptionsView.ShowGroupPanel = false;
gridView1.GroupPanelText = "主面板文本";
// 奇偶行
gridView1.OptionsView.EnableAppearanceEvenRow = true;
//gridView1.Appearance.EvenRow.BackColor = System.Drawing.Color.Green;
gridView1.OptionsView.EnableAppearanceOddRow = true;
//gridView1.Appearance.OddRow.BackColor = System.Drawing.Color.Red;
//gridView1.Appearance.FocusedRow.BackColor = Color.Green;
// 行首列头设置
// 显示列头
gridView1.OptionsView.ShowColumnHeaders = true;
// 自动换行
gridView1.OptionsView.RowAutoHeight = true;
// 列头居中
gridView1.Appearance.HeaderPanel.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
// 数据列居中
gridView1.Appearance.Row.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
// 显示行首
gridView1.OptionsView.ShowIndicator = true;
// 行首宽
gridView1.IndicatorWidth = 40;
// 行首序号
gridView1.CustomDrawRowIndicator += GridView1_CustomDrawRowIndicator;
// 隐藏聚焦行
// 取消点击后虚线框
gridView1.FocusRectStyle = DrawFocusRectStyle.None;
// 禁用单元格选中
gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;
// 禁用选中整行
gridView1.OptionsSelection.EnableAppearanceFocusedRow = false;
// 数据列表选择模式
// 允许多行选择
gridView1.OptionsSelection.MultiSelect = true;
// 选择方式,显示复选框
gridView1.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CheckBoxRowSelect;
// 直接鼠标点击
gridView1.OptionsBehavior.EditorShowMode = DevExpress.Utils.EditorShowMode.MouseDown;
// 只读
gridView1.OptionsBehavior.ReadOnly = true;
// 不可编辑,可拷贝(ReadOnly=true)
gridView1.OptionsBehavior.Editable = false;
// 禁用列头过滤
gridView1.OptionsCustomization.AllowFilter = false;
// 禁用列头排序
gridView1.OptionsCustomization.AllowSort = false;
// 禁用列头移动
gridView1.OptionsCustomization.AllowColumnMoving = false;
// 允许改变列宽
gridView1.OptionsCustomization.AllowColumnResizing = true;
// 禁用标题列分组
gridView1.OptionsCustomization.AllowGroup = false;
// Footer是否显示过滤面板
gridView1.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Never;
// 只显示一层数据
gridView1.LevelTree = 1;
gridView1.ShowOnlyPredefinedDetails = true; // false时,显示所有和绑定数据源相关的数据
// 截断的列头显示提示信息(Caption)
gridView1.OptionsHint.ShowColumnHeaderHints = true;
private void GridView1_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
{
// 隐藏指示图标
e.Info.ImageIndex = -1;
if (e.Info.Kind == DevExpress.Utils.Drawing.IndicatorKind.Header)
{
e.Info.DisplayText = "行号";
}
e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
if (e.Info.IsRowIndicator && e.RowHandle >= 0)
{
e.Info.DisplayText = (e.RowHandle + 1).ToString();
}
}
获取数据
// 获取指定行的数据
var rowHandle = 0;
var entitiy = gridView1.GetFocusedRowCellValue(gridView1.Columns[0]) as DemoClassA;
entitiy = gridView1.GetRow(rowHandle) as DemoClassA;
// 获取指定列的数据
var cellValue = gridView1.GetRowCellValue(rowHandle, "FieldName")?.ToString();
基本事件
// 单行选择时改变事件
gridView1.FocusedRowChanged += GridView1_FocusedRowChanged;
// 多行选择时改变事件
gridView1.SelectionChanged += GridView1_SelectionChanged;
// 空记录提示
gridView1.CustomDrawEmptyForeground += GridView1_CustomDrawEmptyForeground;
private void GridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
{
Console.WriteLine("FocusedRowChanged _" + e.FocusedRowHandle);
if (sender is GridView gridView)
{
if (gridView.GetFocusedRow() is KeyValuePair<int, string> item)
{
labelControl1.Text = item.Value;
}
}
}
private void GridView1_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
{
Console.WriteLine("SelectionChanged " + e.ControllerRow);
}
private void GridView1_CustomDrawEmptyForeground(object sender, CustomDrawEventArgs e)
{
if (sender is GridView gridView)
{
var bindingSource = gridView.DataSource as BindingSource;
if (bindingSource == null || bindingSource.Count == 0)
{
string msg = "空数据!!";
Font font = new Font("宋体", 16, FontStyle.Bold);
// 居中显示
var format = new StringFormat();
format.Alignment = StringAlignment.Center;
e.Graphics.DrawString(msg, font, Brushes.Gray, new PointF(e.Bounds.Width / 2, e.Bounds.Y + 5), format);
}
}
}
自定义单元格显示
gridView1.CustomColumnDisplayText += GridView1_CustomColumnDisplayText;
private void GridView1_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
{
if (e.Value != null && e.Value.ToString().Length > 0)
{
if (e.Column.FieldName == "绑定的属性")
{
e.DisplayText = e.Value.ToString().Length == 3 ? "2" : "000";
}
}
}
自定义单元格颜色
gridView1.CustomDrawCell += GridView1_CustomDrawCell;
private void GridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
{
if (e.Column.FieldName.Equals("绑定属性") && e.Cell is DevExpress.XtraGrid.Views.Grid.ViewInfo.GridCellInfo cellInfo)
{
if (cellInfo.IsDataCell)
{
var value = Convert.ToDouble(cellInfo.CellValue);
if (value < 20)
{
e.Appearance.BackColor = Color.Orange;
}
else if (value < 100)
{
e.Appearance.BackColor = Color.Red;
}
}
}
}
类似于事件 RowCellStyle,但是更稳定。
自定义提示
-
添加自定义控件 ToolTipController
gridControl1.ToolTipController = toolTipController1
-
添加控件的事件 GetActiveObjectInfo
private void toolTipController1_GetActiveObjectInfo(object sender, ToolTipControllerGetActiveObjectInfoEventArgs e)
{
var hitInfo = gridView1.CalcHitInfo(e.ControlMousePosition);
if (hitInfo.RowHandle < 0 || hitInfo.Column == null || hitInfo.HitTest != DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitTest.RowCell)
{
toolTipController1.HideHint();
return;
}
if (hitInfo.Column.FieldName == "PropertyName1")
{
var item = gridView1.GetRow(hitInfo.RowHandle) as DemoClassA;
if (item != null)
{
e.Info = new ToolTipControlInfo("指定标识符A", item.PropertyName2);
}
}
}
鼠标悬停颜色跟踪
_ = new GridViewHelper(gridView1, Color.Green)
{
HoverEnable = true
};
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
/// <summary>
/// GridView帮助类
/// </summary>
public class GridViewHelper
{
private bool _hoverEnable;
/// <summary>
/// true启用悬停效果,false不启用
/// </summary>
public bool HoverEnable
{
get { return _hoverEnable; }
set
{
_hoverEnable = value;
UnRegisterEvent();
if (value)
{
RegisterEvent();
}
else
{
_gridView.RefreshData();
}
}
}
private bool _byRow;
/// <summary>
/// true单行悬停,false单元格悬停
/// </summary>
public bool ByRow
{
get { return _byRow; }
set
{
_byRow = value;
UnRegisterEvent();
if (_hoverEnable)
{
RegisterEvent();
}
}
}
private readonly GridView _gridView;
private readonly Color _hoverColor;
private int _curRowHandle;
private GridColumn _curColumn;
/// <summary>
///
/// </summary>
/// <param name="gridView"></param>
/// <param name="hoverColor">鼠标悬停时颜色</param>
/// <param name="byRow">true单行,false单元格</param>
public GridViewHelper(GridView gridView, Color hoverColor, bool byRow = true)
{
_gridView = gridView;
_hoverColor = hoverColor;
_byRow = byRow;
_curRowHandle = int.MinValue;
}
private void GridView_MouseLeave(object sender, EventArgs e)
{
_curColumn = null;
_curRowHandle = int.MinValue;
_gridView.RefreshData();
}
private void UnRegisterEvent()
{
_gridView.MouseLeave -= GridView_MouseLeave;
_gridView.MouseMove -= GridView_MouseMove;
_gridView.RowCellStyle -= GridView_RowCellStyle;
_gridView.RowStyle -= GridView_RowStyle;
}
private void RegisterEvent()
{
_gridView.MouseLeave += GridView_MouseLeave;
_gridView.MouseMove += GridView_MouseMove;
if (!_byRow)
{
_gridView.RowCellStyle += GridView_RowCellStyle;
}
else
{
_gridView.RowStyle += GridView_RowStyle;
}
}
private void GridView_RowStyle(object sender, RowStyleEventArgs e)
{
if (e.RowHandle == _curRowHandle)
{
e.Appearance.BackColor = _hoverColor;
e.HighPriority = true;
}
}
private void GridView_RowCellStyle(object sender, RowCellStyleEventArgs e)
{
if (e.Column == _curColumn && e.RowHandle == _curRowHandle)
{
e.Appearance.BackColor = _hoverColor;
}
}
private void GridView_MouseMove(object sender, MouseEventArgs e)
{
if (sender is GridView gridView)
{
var info = gridView.CalcHitInfo(e.Location);
var bRefresh = false;
if ((_curColumn != info.Column || _curRowHandle != info.RowHandle) && info.InRow)
{
bRefresh = true;
}
//if (info.InDataRow) v14.2
if (info.InRow)
{
_curColumn = info.Column;
_curRowHandle = info.RowHandle;
}
else
{
_curColumn = null;
_curRowHandle = int.MinValue;
}
if (bRefresh)
{
_gridView.RefreshData();
}
}
}
}
功能扩展
/// <summary>
/// 获取列表中已选择的项
/// </summary>
/// <typeparam name="T">绑定的数据类型</typeparam>
/// <param name="gridview"></param>
/// <returns></returns>
public static IList<T> GetSelectedAllData<T>(this GridView gridview)
{
IList<T> rslt = new List<T>();
// 获取选择行的行号
var rows = gridview.GetSelectedRows();
foreach (var indx in rows)
{
if (gridview.GetRow(indx) is T obj)
{
rslt.Add(obj);
}
}
return rslt;
}
/// <summary>
/// 设置列表选中行
/// </summary>
/// <param name="gridView"></param>
/// <param name="index">从0开始</param>
public static void SetSelectionIndex(this GridView gridView, int index)
{
// 选中整行
gridView.OptionsSelection.EnableAppearanceFocusedRow = true;
// 多行选择模式有效
gridView.ClearSelection();
if (index >= 0)
{
// 聚焦
gridView.FocusedRowHandle = index;
// 选中
gridView.SelectRow(index);
}
else
{
gridView.FocusedRowHandle = -1;
gridView.UnselectRow(0);
}
}
/// <summary>
/// 设置列表可编辑
/// </summary>
/// <param name="gridView"></param>
/// <param name="fieldNames">允许编辑的列的FieldName</param>
public static void CanEdit(this GridView gridView, params string[] fieldNames)
{
gridView.OptionsBehavior.ReadOnly = false;
gridView.OptionsBehavior.Editable = true;
foreach (GridColumn item in gridView.Columns)
{
if (!fieldNames.Contains(item.FieldName))
{
item.OptionsColumn.ReadOnly = true;
item.OptionsColumn.AllowEdit = false;
}
}
}
/// <summary>
/// 列表复选框全选
/// </summary>
/// <param name="gridView"></param>
/// <param name="fieldName">复选框的FieldName</param>
public static void CheckedAll(this GridView gridView, string fieldName)
{
int count = gridView.DataRowCount;
for (int i = 0; i < count; i++)
{
gridView.SetRowCellValue(i, gridView.Columns[fieldName], true);
}
gridView.GridControl.Refresh();
}
/// <summary>
/// 列表复选框全非选
/// </summary>
/// <param name="gridView"></param>
/// <param name="fieldName">复选框的FieldName</param>
public static void UnCheckedAll(this GridView gridView, string fieldName)
{
int count = gridView.DataRowCount;
for (int i = 0; i < count; i++)
{
gridView.SetRowCellValue(i, gridView.Columns[fieldName], false);
}
gridView.GridControl.Refresh();
}
绑定指定字段
绑定嵌套属性
FieldName可设置为:PorpertyName1.NestedPropertyName。
添加复选框列
若GridMultiSelectMode没有CheckBoxRowSelect,可以手动添加CheckEdit。
表头合并
在设计页面,把默认的GridView转换成BandedGridView。然后在Run Designer中拖动编辑即可。
列中添加功能按钮
默认ColumnEdit为空,可选择需要的按钮,比如Button。
列中不绑定对象,可以把 TextEditStyle 设置为 HideTextEditor。
具体按钮设置如下:
按钮响应声明:
按钮响应逻辑:
private void repositoryItemButtonEdit1_ButtonClick(object sender, ButtonPressedEventArgs e)
{
var row = (DemoClass)gridView1.GetFocusedRow();
if (e.Button.Caption == "编辑")
{
// TODO
}
else if (e.Button.Caption == "删除")
{
// TODO
}
}
TreeList
绑定数据与图标
using DevExpress.XtraEditors;
using DevExpress.XtraTreeList.Nodes;
private List<TreeNodeDto> _data;
private void Form1_Load(object sender, EventArgs e)
{
_data = SalesDataGenerator.CreateData();
treeList1.Columns.Clear();
treeList1.Nodes.Clear();
treeList1.KeyFieldName = "ID";
treeList1.ParentFieldName = "ParentID";
treeList1.OptionsBehavior.PopulateServiceColumns = false;
treeList1.OptionsBehavior.AutoPopulateColumns = true;
treeList1.OptionsBehavior.ExpandNodeOnDrag = false;
treeList1.OptionsBehavior.Editable = false; // 不可编辑
treeList1.DataSource = _data;
treeList1.OptionsView.ShowColumns = false; // 隐藏列标头
treeList1.OptionsView.ShowHorzLines = false;// 隐藏水平表格线
treeList1.OptionsView.ShowVertLines = false;// 隐藏垂直表格线
treeList1.OptionsView.ShowIndicator = false;// 隐藏节点指示器面板
treeList1.OptionsView.ShowCheckBoxes = false; // 隐藏勾选框
treeList1.OptionsView.ShowFocusedFrame = true; // 焦点虚框
treeList1.OptionsSelection.EnableAppearanceFocusedCell = false; // 禁用单元格选中
treeList1.OptionsSelection.EnableAppearanceFocusedRow = false; // 禁用整行选中
treeList1.OptionsLayout.StoreAppearance = true;
treeList1.OptionsMenu.EnableColumnMenu = false;
treeList1.OptionsMenu.EnableFooterMenu = false;
treeList1.OptionsMenu.ShowAutoFilterRowItem = false;
treeList1.SelectImageList = imageList1;
treeList1.Columns["Tag"].Visible = false; // 设置列隐藏
treeList1.RowHeight = 30;
treeList1.ExpandAll();
}
同步图标索引
private void TreeList1_GetSelectImage(object sender, DevExpress.XtraTreeList.GetSelectImageEventArgs e)
{
if (e.Node == null)
{
return;
}
var data = treeList1.GetDataRecordByNode(e.Node) as TreeNodeDto;
if (data != null)
{
e.Node.ImageIndex = data.ImageIndex;
e.Node.SelectImageIndex = data.ImageIndex;
}
}
双击
private void TreeList1_MouseDoubleClick(object sender, MouseEventArgs e)
{
var node = treeList1.CalcHitInfo(e.Location).Node;
if (node == null)
{
return;
}
var data = treeList1.GetDataRecordByNode(node) as TreeNodeDto;
node.SelectImageIndex = node.ImageIndex;
lbMsg.Text = data.DisplayText;
}
DataSource强制更新
private void BtnAdd_Click(object sender, EventArgs e)
{
_data.Add(new TreeNodeDto() { DisplayText = "test", ParentID = -1, ID = 100 });
_data.Add(new TreeNodeDto() { DisplayText = "test2", ParentID = -1, ID = 101 });
// 如果Data Source 有更改
treeList1.RefreshDataSource();
treeList1.Update();
}
public static List<TreeNodeDto> CreateData()
{
List<TreeNodeDto> data = new List<TreeNodeDto>();
data.Add(new TreeNodeDto(1, -1, TreeNodeEnum.TreeNode, typeof(Form1)));
data.Add(new TreeNodeDto(2, -1, TreeNodeEnum.TreeNode2, typeof(Form1)));
data.Add(new TreeNodeDto(3, -1, TreeNodeEnum.TreeNode3, typeof(Form1)));
data.Add(new TreeNodeDto(4, 3, TreeNodeEnum.SubNode1, typeof(Form1)));
data.Add(new TreeNodeDto(5, 4, TreeNodeEnum.ChildNode, typeof(Form1)));
data.Add(new TreeNodeDto(6, 4, TreeNodeEnum.ChildNode2, typeof(Form1)));
data.Add(new TreeNodeDto(7, 4, TreeNodeEnum.ChildNode3, typeof(Form1)));
return data;
}
public class TreeNodeDto
{
/// <summary>
/// 节点唯一ID
/// </summary>
public int ID { get; set; }
/// <summary>
/// 父节点ID
/// </summary>
public int ParentID { get; set; }
/// <summary>
/// 节点名称
/// </summary>
public string DisplayText { get; set; }
/// <summary>
/// 节点标签
/// </summary>
public object Tag { get; set; }
/// <summary>
/// 节点图标索引
/// </summary>
public int ImageIndex { get; set; }
public TreeNodeDto() {}
public TreeNodeDto(int id, int parentId, TreeNodeEnum nodeEnum, Type ucType, int imageIndex = 1) : this(id, parentId, nodeEnum.GetEnumDescription(), ucType, imageIndex)
{
}
public TreeNodeDto(int id, int parentId, string name, Type ucType, int imageIndex = 1)
{
ID = id;
ParentID = parentId;
DisplayText = name;
if (ucType == typeof(Nullable))
{
Tag = null;
}
else
{
Tag = ucType;
}
ImageIndex = imageIndex;
}
}
public enum TreeNodeEnum
{
[Description("Node1")]
TreeNode,
[Description("Node2")]
TreeNode2,
[Description("Node3")]
TreeNode3,
[Description("SubNode1")]
SubNode1,
[Description("ChildNode1")]
ChildNode,
[Description("ChildNode2")]
ChildNode2,
[Description("ChildNode3")]
ChildNode3,
}
PropertyGridControl
public DemoClass MyDemo { get; set; }
public Form1()
{
InitializeComponent();
MyDemo = new DemoClass();
}
private void Form1_Load(object sender, EventArgs e)
{
propertyDescriptionControl1.PropertyGrid = propertyGridControl1;
propertyGridControl1.SelectedObject = MyDemo;
}
public class DemoClass
{
private int _myVar = 90;
[Category("Category1")]
[DisplayName("整数")]
public int P_Integer
{
get { return _myVar; }
set { _myVar = value; }
}
private bool _bValue;
[Category("Category1")]
public bool P_Boolean
{
get { return _bValue; }
set { _bValue = value; }
}
private string _strValue;
[DisplayName("字符串")]
[Description("字符串描述")]
public string P_String
{
get { return _strValue; }
set { _strValue = value; }
}
}
DXValidationProvider
验证控件。
dxValidatationProvider作为一个验证控件,可以同时对多个控件进行数据验证。
但是对同一个控件的验证,则需要分别写在不同的dxValidatationProvider中,防止被覆盖。
XtraMessageBox
#region ShowInfo
public static void ShowInfo(this XtraForm form, string message)
{
XtraMessageBox.Show(message, "Info", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
}
public static void ShowDebug(this XtraForm form, string message)
{
XtraMessageBox.Show(message, "Debug", System.Windows.Forms.MessageBoxButtons.YesNo);
}
public static bool ShowConfirm(this XtraForm form, string message)
{
var dlg = XtraMessageBox.Show(message, "Confirm", System.Windows.Forms.MessageBoxButtons.OKCancel);
return dlg == System.Windows.Forms.DialogResult.OK;
}
public static void ShowInfo(this XtraUserControl control, string message)
{
XtraMessageBox.Show(message, "Info", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
}
public static void ShowDebug(this XtraUserControl control, string message)
{
XtraMessageBox.Show(message, "Debug", System.Windows.Forms.MessageBoxButtons.YesNo);
}
public static bool ShowConfirm(this XtraUserControl control, string message)
{
var dlg = XtraMessageBox.Show(message, "Confirm", System.Windows.Forms.MessageBoxButtons.OKCancel);
return dlg == System.Windows.Forms.DialogResult.OK;
}
#endregion
XtraScrollableControl
有内置滚动条的面板。
其中控件不能设置 Dock=Fill。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?