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()});}
运行截图:
源码下载: