在 C1PropertyGrid 中使用自定义编辑控件

发布时间:2013/06/20 00:06 发布者:jian

返回博客中心

C1 控件套包中为 WPF 和 Silverlight 平台提供了 C1PropertyGrid 控件,可以通过该控件来设置控件属性,本文主要演示如何在 C1PropertyGrid for Silverlight 中使用自定义的属性编辑控件,我们将使用的是基于 C1ComboBox 的自定义编辑器控件。

核心代码是创建一个继承于 C1ComboBox ,并实现 ITypeEditorControl 接口的控件,代码如下:

    public class ComboBoxEditor : C1ComboBox, ITypeEditorControl
    {
        public void Attach(PropertyAttribute property)
        {
            // 设置自定义控件与属性的绑定关系
            var binding = new System.Windows.Data.Binding(property.PropertyInfo.Name)
            {
                Mode = System.Windows.Data.BindingMode.TwoWay,
                Source = property.SelectedObject,
                ValidatesOnExceptions = true,
            };
            this.SetBinding(ComboBoxEditor.SelectedItemProperty, binding);
        }
        public ITypeEditorControl Create()
        {
            ComboBoxEditor cbe = new ComboBoxEditor();
            // 绑定 C1ComboBox 的 ItemsSource 属性
            LoadItems(cbe);
            return cbe;
        }
        
        private void LoadItems(ComboBoxEditor cbe)
        {
            List<KeyValuePair<string, string>> items = new List<KeyValuePair<string, string>>();
            items.Add(new KeyValuePair<string, string>("XA", "西安"));
            items.Add(new KeyValuePair<string, string>("BJ", "北京"));
            items.Add(new KeyValuePair<string, string>("TJ", "天津"));
            items.Add(new KeyValuePair<string, string>("SH", "上海"));
            items.Add(new KeyValuePair<string, string>("CQ", "重庆"));
            cbe.ItemsSource = items;
            cbe.DisplayMemberPath = "Value";
            cbe.SelectedValuePath = "Key";
        }
        public void Detach(PropertyAttribute property)
        {
            
        }
        public bool Supports(PropertyAttribute Property)
        {
            return Property.PropertyInfo.PropertyType == typeof(System.String);
        }
        public event System.ComponentModel.PropertyChangedEventHandler ValueChanged;
    }

 

在页面后台代码中使用自定义的 ComboBoxEditor 控件,代码如下:

    public MainPage()
    {
        InitializeComponent();
            Item item = new Item();
          
        c1PropertyGrid1.AvailableEditors.Insert(0, new ComboBoxEditor());            
        c1PropertyGrid1.SelectedObject = item;
        c1PropertyGrid1.PropertyAttributes.Add(new PropertyAttribute()
        {
            MemberName = "City",
            Editor = new ComboBoxEditor()
        });
    }

 

运行截图:

C1PropertyGrid

 

源码下载:


关于葡萄城

赋能开发者!葡萄城是专业的集开发工具、商业智能解决方案、低代码开发平台于一身的软件和服务提供商,为超过 75% 的全球财富 500 强企业提供服务。葡萄城专注控件软件领域30年,希望通过模块化的开发控件、灵活的低代码应用开发平台等一系列开发工具、解决方案和服务,帮助开发者快速响应复杂多变的业务需求,最大程度地发挥开发者的才智和潜能,让开发者的 IT 人生更从容更美好。

了解详情,请访问葡萄城官网