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;
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;
XtraMessageBox.Show(listBoxControl.SelectedValue.ToString());
}
绑定模式会使listInfo的变化反应到控件显示,且listBoxControl1.Items是没有数据的,但不影响SelectedValueChanged等操作。
若listInfo是可通知的对象集合(BindingList、ObservableCollection),listInfo.Add(item)会自动更新listBoxControl1的内容;
若是List集合,需要手动刷新控件:listBoxControl1.Refresh();
详情查看Winform 属性值绑定、转换、实时通知
ComboBoxEdit
下拉列表。可绑定任意类型的项目集合,项目显示文本取决于类型的ToString()的内容。
var list= EnumExtends.GetEnumResource<EnumType>();
comboBoxEdit1.Properties.Items.AddRange(list);
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;
}
}
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;
}
}
}
}
自定义提示
-
添加自定义控件 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
}
}
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
验证控件
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