DevExpress,LayoutControl,TreeList,GridControl等

1.显示边框进行折叠

选择一个layoutControlGroupX 将其GroupBordersVisible设置成True,将TextVisiable=True

2. TreeList

2.1需要绑定的数据有ParentFieldName,KeyFieldName,

2.2.1.TeeList前面的连线
启动程序中添加DevExpress.BonusSkins.v13.1.dll
Main中进行注册

     [STAThread]
        static void Main(params String[] args)
        {
            DevExpress.UserSkins.BonusSkins.Register();
            DevExpress.Skins.SkinManager.EnableFormSkins();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            if (args.Length>=1 && args[0]=="test")
            {
                Application.Run(new Form1());
            }else
            {
                Application.Run(new F.Studio.DevExpressUI.frmLogin());
            }
        }
View Code

 需要设置LookAndFeel(比方Blue),

将UseDefaultLookAndFeel设置成False
//显示checkBox,并执行递归选择

treeList1.OptionsBehavior.AllowRecursiveNodeChecking = true;
treeList1.OptionsView.ShowCheckBoxes = true;
//参考:http://blog.sina.com.cn/s/blog_53b58e7c0101aclk.html

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using F.Studio.Prime.IService;
using F.Studio.Prime.EFModel;
using DevExpress.XtraTreeList.Nodes;

namespace F.Studio.DevExpressUI
{
    public partial class frmFuncsConfigEdit : frmEditBase
    {
        public Sys_FuncsConfig ModifyConfig { get; set; }

        public frmFuncsConfigEdit()
        {
            InitializeComponent();
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
            
            #region 配置TreeList


            imageList1.Images.Add( Properties.Resources.folder);
            imageList1.Images.Add( Properties.Resources.folder_open);
            imageList1.Images.Add( Properties.Resources.func);
            imageList1.Images.Add( Properties.Resources.tag_16x16);
            imageList1.Images.Add( Properties.Resources.question_16x16);

          
            treeList1.StateImageList = imageList1;
            treeList1.SelectImageList = imageList1;
            treeList1.ColumnsImageList = imageList1;
          
            //显示checkBox,并执行递归选择
            
            treeList1.OptionsView.ShowCheckBoxes = true;
            treeList1.OptionsBehavior.AllowIndeterminateCheckState = false;
            treeList1.OptionsBehavior.AllowRecursiveNodeChecking = false;
            treeList1.OptionsBehavior.Editable = false;
            
            treeList1.AfterCheckNode += (s, e) =>
            {
                Console.WriteLine(e.Node.SelectImageIndex);
            };
            treeList1.NodesReloaded += (s, e) =>
            {
                //到这里完成全部Node的挂接!
                Console.WriteLine("NodesReloaded");
                
                SetTreeListCheckState();
                treeList1.OptionsBehavior.AllowRecursiveNodeChecking = true;
            };
            treeList1.CreateCustomNode += (s, e) => {
                var tag = e.Tag;
                Console.WriteLine("CreateCustomNode");
                
            };
            treeList1.NodeChanged += (s, e) => {
                Console.WriteLine("NodeChanged");
              
            };
            treeList1.FocusedNodeChanged += (s, e) => {

                var list= treeList1.GetDataRecordByNode(e.Node);
               
                childBindingSource.DataSource = list;
            };
            #endregion


            
        }
        public frmFuncsConfigEdit(Sys_FuncsConfig config):this()
        {
            sys_FuncsConfigBindingSource.DataSource = config;
            IsModify = true;
            ModifyConfig = config;

   
        }
        private void SetTreeListCheckState()
        {
            Queue<TreeListNode> queue = new Queue<TreeListNode>();
            foreach (TreeListNode node in treeList1.Nodes)
            {
                queue.Enqueue(node);
            };

            while (queue.Count > 0)
            {
                var node= queue.Dequeue();
                
                var isChecked=(bool)node.GetValue("IsChecked");
                node.Checked = isChecked;
                 //treeList1.SetNodeCheckState(node, isChecked ? CheckState.Checked : CheckState.Unchecked, false);
                foreach (TreeListNode child in node.Nodes)
                {
                    queue.Enqueue(child);
                }
            }
        
        }
        private void frmFuncsConfigEdit_Load(object sender, EventArgs e)
        {


            Func<List<SysResourceInfo>> fun = () =>
            {
                return SysResourceInfo.Build();
            };
            var list = InvokeService<List<SysResourceInfo>>(fun);
           
            
            if (!IsModify)
            {
                sys_FuncsConfigBindingSource.AddNew();
            }
            else//修改状态
            {
                
                string wehre=string.Format("it.ConfigId={0}",ModifyConfig.ConfigId);
                var configItems= Fetch<IFuncsConfigItemsService>().GetList(wehre, "it.RecId");
                list.ForEach(item => {
                    if (item.ResourceType == "目录") return;
                    if (configItems.Any(ent => ent.ResourceId == item.FuncId))
                    {
                        item.IsChecked = true;
                    }
                });

            }
            sysResourceInfoBindingSource.DataSource = list;
            Console.WriteLine(treeList1.AllNodesCount);
       
           
        }

        private void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
           
            foreach (TreeListNode node in treeList1.Nodes)
            {
                Console.WriteLine(node.ToString());
            }
        }

        private void btnCancel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }
    }
}
View Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using F.Studio.Prime.IService;
using F.Studio.Prime.EFModel;
using DevExpress.XtraTreeList.Nodes;
using F.Studio.Infrastructure;

namespace F.Studio.DevExpressUI
{
    public partial class frmFuncsConfigEdit : frmEditBase
    {
        public Sys_FuncsConfig ModifyConfig { get; set; }

        public frmFuncsConfigEdit()
        {
            InitializeComponent();
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
            
            #region 配置TreeList


            imageList1.Images.Add( Properties.Resources.folder);
            imageList1.Images.Add( Properties.Resources.folder_open);
            imageList1.Images.Add( Properties.Resources.func);
            imageList1.Images.Add( Properties.Resources.tag_16x16);
            imageList1.Images.Add( Properties.Resources.question_16x16);



            
            treeList1.StateImageList = imageList1;
            treeList1.SelectImageList = imageList1;
            treeList1.ColumnsImageList = imageList1;
          
            //显示checkBox,并执行递归选择
            
            treeList1.OptionsView.ShowCheckBoxes = true;
            treeList1.OptionsBehavior.AllowIndeterminateCheckState = false;
            treeList1.OptionsBehavior.AllowRecursiveNodeChecking = true;
            treeList1.OptionsBehavior.Editable = false;
            
          
            treeList1.AfterCheckNode += (s, e) =>
            {
                treeList1.FocusedNode = e.Node;
                Console.WriteLine("AfterCheckNode!");
                var r = treeList1.GetDataRecordByNode(e.Node) as SysResourceInfo;
 
                r.IsChecked = e.Node.Checked;
                treeList1.CloseEditor();

               #region (废弃) 如果窗体取消选择,那么取消窗体下的按钮
                //if (!e.Node.Checked)
                //{
                //    if (r.ResourceType == "窗体")
                //    {
                //        r.Buttons.ForEach(ent => ent.IsChecked = false);
                //        buttonsBindingSource.ResetBindings(true);
                //    }
                //}
               #endregion


            };
            treeList1.NodesReloaded += (s, e) =>
            {
                //到这里完成全部Node的挂接!
                Console.WriteLine("NodesReloaded");

                SetTreeListCheckState();
               
            };
            treeList1.CreateCustomNode += (s, e) => {
                //var tag = e.Tag;
                //Console.WriteLine("CreateCustomNode");
                
            };
            treeList1.NodeChanged += (s, e) => {
                //Console.WriteLine("NodeChanged");
              
            };
            treeList1.FocusedNodeChanged += (s, e) => {

                var list= treeList1.GetDataRecordByNode(e.Node);
               
               buttonsBindingSource.DataSource = list;
            };

            buttonsBindingSource.CurrentItemChanged += (s, e) => {
                //var btn= buttonsBindingSource.Current as SysButtonInfo;
                //if (btn == null) return;
                //Console.WriteLine("CurrentItemChanged:" + btn.IsChecked);
            };
            #endregion


            repositoryItemCheckEdit1.CheckedChanged += (s, e) => {
                Console.WriteLine("CheckedChanged:");
                var btn= gridView1.GetFocusedRow() as SysButtonInfo;
                var parent= btn.Parent as SysResourceInfo;
              
                if((s as CheckEdit).Checked)
                {
                    parent.Node.Checked = true;
                        
                }

               gridView1.CloseEditor();  
               gridView1.UpdateCurrentRow(); 
            };
        }
        public frmFuncsConfigEdit(Sys_FuncsConfig config):this()
        {
            sys_FuncsConfigBindingSource.DataSource = config;
            IsModify = true;
            ModifyConfig = config;

   
        }
        private void SetTreeListCheckState()
        {
            Queue<TreeListNode> queue = new Queue<TreeListNode>();
            foreach (TreeListNode node in treeList1.Nodes)
            {
                queue.Enqueue(node);
            };

            while (queue.Count > 0)
            {
                var node= queue.Dequeue();
                var obj= treeList1.GetDataRecordByNode(node) as SysResourceInfo; 
                var isChecked=(bool)node.GetValue("IsChecked");
                obj.Node = node;//建立引用
                node.Checked = isChecked;
                if (isChecked)
                {
                    var cur = node;
                    while (cur.ParentNode != null)
                    {
                        var rnode = treeList1.GetDataRecordByNode(cur) as SysResourceInfo;
                        Console.WriteLine(rnode.Title);
                        cur.ParentNode.Checked = true;
                        cur = cur.ParentNode;
                    }
                }
                 treeList1.SetNodeCheckState(node, isChecked ? CheckState.Checked : CheckState.Unchecked, false);
                foreach (TreeListNode child in node.Nodes)
                {
                    queue.Enqueue(child);
                }
            }
        
        }
        /// <summary>
        /// 同步接点状态到绑定数据源
        /// </summary>
        private void SyncCheckState()
        {
            Queue<TreeListNode> queue = new Queue<TreeListNode>();
            foreach (TreeListNode node in treeList1.Nodes)
            {
                queue.Enqueue(node);
            };

            while (queue.Count > 0)
            {
                var node = queue.Dequeue();
                var obj = treeList1.GetDataRecordByNode(node) as SysResourceInfo;
                obj.IsChecked = node.Checked;
                foreach (TreeListNode child in node.Nodes)
                {
                    queue.Enqueue(child);
                }
            }
        }

        private void frmFuncsConfigEdit_Load(object sender, EventArgs e)
        {


            Func<List<SysResourceInfo>> fun = () =>
            {
                return SysResourceInfo.Build();
            };
            var list = InvokeService<List<SysResourceInfo>>(fun);

           
            
            if (!IsModify)
            {
                sys_FuncsConfigBindingSource.AddNew();
            }
            else//修改状态
            {
                
                string wehre=string.Format("it.ConfigId={0}",ModifyConfig.ConfigId);
                var configItems= Fetch<IFuncsConfigItemsService>().GetList(wehre, "it.RecId");
                list.ForEach(item => {
                    if (item.ResourceType == "目录") return;
                    if (configItems.Any(ent => ent.ResourceId == item.FuncId))
                    {
                        item.IsChecked = true;

                    }
                    //设置按钮
                    item.Buttons.ForEach(btn =>
                    {
                        if (configItems.Any(ent1 => ent1.ResourceId == btn.FuncId))
                        {
                            btn.IsChecked = true;
                        }
                    });
                });

            }
            sysResourceInfoBindingSource.DataSource = list;


            treeList1.ExpandAll();
            //SetTreeListCheckState();
       
           
        }

        private void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                sys_FuncsConfigBindingSource.EndEdit();
                sysResourceInfoBindingSource.EndEdit();
                buttonsBindingSource.EndEdit();
                gridView1.CloseEditor();

                var ent = sys_FuncsConfigBindingSource.Current as Sys_FuncsConfig;
                if (string.IsNullOrWhiteSpace(ent.ConfigName)) throw new Exception("请提供配置名!");
 
            
                var srv = ServiceLocator.Fetch<IFuncsConfigService>();
                if (IsModify)
                {
                    srv.Update(ent);
                }
                else
                {
                    var newEnt = srv.Add(ent);
                    ent.ConfigId = newEnt.ConfigId;

                    base.NewRecord = newEnt;
                }

                #region 更新配置



                SyncCheckState();
                var res = (sysResourceInfoBindingSource.DataSource as List<SysResourceInfo>).Where(entTmp=>entTmp.ResourceType!="目录").ToList();

                
                #region(作废) 被"目录"类型节点递归选中的节点做额外处理
                //var nodes = treeList1.GetAllCheckedNodes();
                //nodes.ForEach(node =>
                //{
                //    var resIt = treeList1.GetDataRecordByNode(node) as SysResourceInfo;
                //    if (resIt.ResourceType != "目录")
                //    {
                //        resIt.IsChecked = true;
                       
                //    }
                //});
                #endregion

                Action act = () => {

                    var newResList = new List<Sys_FuncsConfigItems>();

                    foreach (var r in res)
                    {
                       
                        var newRes = new Sys_FuncsConfigItems();
                        newRes.ResourceId = r.FuncId;
                        newRes.ResourceType = r.ResourceType;
                        newRes.ConfigId = ent.ConfigId;
                        if (r.IsChecked.Value)
                        {
                            newResList.Add(newRes);
                        }

                        foreach (var btn in r.Buttons)
                        {
                            if (btn.IsChecked.Value)
                            {
                                var newBtnRes = new Sys_FuncsConfigItems();
                                newBtnRes.ResourceId = btn.FuncId;
                                newBtnRes.ResourceType = btn.ResourceType;
                                newBtnRes.ConfigId = ent.ConfigId;
                                newResList.Add(newBtnRes);
                            }
                        }
                    }
                    ServiceLocator.Fetch<IFuncsConfigItemsService>().SetConfigItems(newResList, ent);
                };
                InvokeService(act);

                #endregion
                DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            catch (Exception ex)
            {
                ErrMsg(ex.Message);

            }

        }

        private void btnCancel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }
    }
}
View Code

 展开关闭图标

           imgList = new ImageList(this.components);
            imgList.Images.Add(Properties.Resources.folder);
            imgList.Images.Add(Properties.Resources.folder_open);
            treeList1.SelectImageList = imgList;
            treeList1.StateImageList = imgList;
            
            treeList1.AfterCollapse += (s, e) => {
                e.Node.ImageIndex = 0;
                e.Node.SelectImageIndex = 0;
            };
            treeList1.AfterExpand += (s, e) => {
                e.Node.ImageIndex = 1;
                e.Node.SelectImageIndex = 1;
            };
View Code

 3.GridControl

 3.1.1添建按钮列->参考:http://www.cnblogs.com/zeroone/p/3534783.html

3.1.2 下拉框编辑->http://www.cnblogs.com/zeroone/p/3606224.html

 3.2 设置参考列:http://blog.csdn.net/nanchuan/article/details/7664070

            gridView1.CustomColumnDisplayText += (s, e) =>
            {
                if (e.Column.FieldName == "FuncConfigId")
                {
                    var list = FuncsConfigLookUp.Value;
                    if (list != null)
                    {
                        var it = list.FirstOrDefault(ent => ent.ConfigId == int.Parse(e.Value.ToString()));
                        if (it != null) e.DisplayText = it.ConfigName;
                    }
                }
            };
View Code

3.3 设置计算列,分组会总等
参考:http://blog.csdn.net/lenovouser/article/details/7405577

gridColumn1.UnboundType = DevExpress.Data.UnboundColumnType.Decimal;
gridColumn1.UnboundExpression = "[Amount] * ToDouble(SubString([CostPerUnit],0, CharIndex('(',[CostPerUnit])))";
gridView1.GroupSummary.Add(SummaryItemType.Sum, "gridColumn1", gridView1.Columns["gridColumn1"],"组计:{0}");
注:gridColumn1是一个未帮定列,另外需要开启gridView.OptionsView.ShowFooter=True

3.4判断gridControl 的那个列的单元格被双击
 

    gridControl1.MouseDoubleClick += (s, e) =>
            {
                if (e.Button == System.Windows.Forms.MouseButtons.Left)
                {
                    GridHitInfo hInfo = gridView1.CalcHitInfo(new Point(e.X, e.Y));
                    if (!hInfo.InRow) return; //确保点的是数据行而不是标头
                   
                    var ent = qSymptomRepositoryItemBindingSource.Current as Q_SymptomRepositoryItem;
                    if (ent == null) return;

                    //hInfo.Column==null 标示点了行头
                    if (hInfo.Column!=null && hInfo.Column.Caption == "图片")
                    {
                        var img=gridView1.GetFocusedValue() as Image;
                        new frmPhotoDetail(img).ShowDialog();
                        return;
                    }
                   
                    //双击其他标示修改
                    btnModify.PerformClick();
                    
                }
            };
View Code

3.5 启用滚动条 gridView1.OptionsView.ColumnAutoWidth = false;

4.窗体继承

4.1.如果显示设计时错误,需要把两个partial 类的父类都设置下
4.2.如果father是泛型类那么会一直显示设计时错误

4.3.父亲窗体中用From_Load 或重写了OnLoad时,里面不要写代码,如果要写需要加入if(!DesignMode){...}
4.4.在继承窗体上增加按钮,无法显示

5.样式与中文包


将zn-CN 复制到运行目录 执行下列代码

        /// </summary>
        [STAThread]
        static void Main(params String[] args)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("zh-CN");
            DevExpress.UserSkins.BonusSkins.Register();
            DevExpress.Skins.SkinManager.EnableFormSkins();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (args.Length >= 1 && args[0] == "test")
            {
                Application.Run(new Form1());
            }
            else
            {
                Application.Run(new F.Studio.DevExpressUI.frmLogin());
            }
        }
View Code

 6.DateEdit显示时间

DateEdit如果开启Vista模式并显示日期+时间模式 问题,以前没有涉及过,借机看一下,记录如下:
设置为Vista显示模式(如下图)

 参考 :http://www.cnblogs.com/xiaofengfeng/archive/2011/09/07/2169691.html

设置以下属性
dateEdit1.Properties.VistaDisplayMode = DevExpress.Utils.DefaultBoolean.True;
dateEdit1.Properties.VistaEditTime = DevExpress.Utils.DefaultBoolean.True;

设置显示长日期模式(日期+时间):
dateEdit1.Properties.DisplayFormat.FormatString="g"
dateEdit1.Properties.DisplayFormat.FormatType=DateTime
dateEdit1.Properties.EditFormat.FormatString="g"
dateEdit1.Properties.EditFormat.FormatType=DateTime

------------------------------------------------------------------

dateEdit1.Properties.VistaDisplayMode = DevExpress.Utils.DefaultBoolean.True;
dateEdit1.Properties.VistaEditTime = DevExpress.Utils.DefaultBoolean.True;
dateEdit1.Properties.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
dateEdit1.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
dateEdit1.Properties.EditFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
dateEdit1.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
dateEdit1.Properties.EditMask = "yyyy-MM-dd HH:mm:ss";



设置为Vista模式时,如果要显示日期+时间的长日期模式,还需要设置:

VistaTimeProperties.DisplayFormat
VistaTimeProperties.EditFormat

7.treeListLookUpEdit禁止文本框输入

  catalogIdSpinEdit.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;

原文地址:https://www.cnblogs.com/wdfrog/p/4015309.html