欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PropertyGrid自定义控件使用详解

程序员文章站 2023-11-17 10:09:28
propertygrid是一个很强大的控件,使用该控件做属性设置面板的一个好处就是你只需要专注于代码而无需关注ui的呈现,propertygrid会默认根据变量类型选择合适...

propertygrid是一个很强大的控件,使用该控件做属性设置面板的一个好处就是你只需要专注于代码而无需关注ui的呈现,propertygrid会默认根据变量类型选择合适的控件显示。但是这也带来了一个问题,就是控件的使用变得不是特别灵活,主要表现在你无法根据你的需求很好的选择控件,比如当你需要用slider控件来设置int型变量时,propertygrid默认的模板选择器是不支持的。网上找了许多资料基本都是介绍winform的实现方式,主要用到了iwindowfromservice这个接口,并未找到合适的适合wpf的demo,后来在参考了devexpress的官方demo之后我做了一个基于wpf和dev 16.2的propertygrid demo,基本实现了上述功能。

为了实现这一点,需要自定义一个datatemplateseletor类,这也是本文的核心代码。

1.创建一个custompropertygrid自定义控件:

<usercontrol
  x:class="propertygriddemo.propertygridcontrol.custompropertygrid"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:dxprg="http://schemas.devexpress.com/winfx/2008/xaml/propertygrid"
  xmlns:local="clr-namespace:propertygriddemo.propertygridcontrol"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  d:designheight="300"
  d:designwidth="300"
  mc:ignorable="d">
  <usercontrol.resources>
    <resourcedictionary>
      <resourcedictionary.mergeddictionaries>
        <!-- 资源字典 -->
        <resourcedictionary source="../propertygridcontrol/dynamicallyassigndataeditorsresources.xaml" />
      </resourcedictionary.mergeddictionaries>
    </resourcedictionary>
  </usercontrol.resources>
  <grid>
    <!-- propertydefinitionstyle:定义属性描述的风格模板 -->
    <!-- propertydefinitiontemplateselector:定义一个模板选择器,对应一个继承自datatemplateselector的类 -->
    <!-- propertydefinitionssource:定义一个获取数据属性集合的类,对应一个自定义类(本demo中对应dataeditorsviewmodel) -->
    <dxprg:propertygridcontrol
      x:name="propertygridcontrol"
      margin="24"
      datacontextchanged="propertygridcontrol_datacontextchanged"
      expandcategorieswhenselectedobjectchanged="true"
      propertydefinitionstyle="{staticresource dynamicallyassigndataeditorspropertydefinitionstyle}"
      propertydefinitiontemplateselector="{staticresource dynamicallyassigndataeditorstemplateselector}"
      propertydefinitionssource="{binding path=properties, source={staticresource demodataprovider}}"
      showcategories="true"
      showdescriptionin="panel" />
  </grid>
</usercontrol>

该控件使用的资源字典如下:

<resourcedictionary
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors"
  xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid"
  xmlns:dxprg="http://schemas.devexpress.com/winfx/2008/xaml/propertygrid"
  xmlns:local="clr-namespace:propertygriddemo.propertygridcontrol"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  mc:ignorable="d">

  <local:dynamicallyassigndataeditorstemplateselector x:key="dynamicallyassigndataeditorstemplateselector" />
  <local:dataeditorsviewmodel x:key="demodataprovider" />

  <datatemplate x:key="descriptiontemplate">
    <richtextbox
      x:name="descriptionrichtextbox"
      minwidth="150"
      horizontalcontentalignment="stretch"
      background="transparent"
      borderthickness="0"
      foreground="{binding path=(textelement.foreground), relativesource={relativesource templatedparent}}"
      isreadonly="true"
      istabstop="false" />
  </datatemplate>
  <datatemplate x:key="descriptiontemplate">
    <richtextbox
      x:name="descriptionrichtextbox"
      minwidth="150"
      horizontalcontentalignment="stretch"
      background="transparent"
      borderthickness="0"
      foreground="{binding path=(textelement.foreground), relativesource={relativesource templatedparent}}"
      isreadonly="true"
      istabstop="false" />
  </datatemplate>

  <!-- 设置控件的全局样式和数据绑定 -->
  <style x:key="dynamicallyassigndataeditorspropertydefinitionstyle" targettype="dxprg:propertydefinition">
    <setter property="path" value="{binding name}" />
    <!--<setter property="header" value="{binding converter={staticresource propertydescriptortodisplaynameconverter}}"/>-->
    <setter property="description" value="{binding}" />
    <setter property="descriptiontemplate" value="{staticresource descriptiontemplate}" />
  </style>
  <style x:key="descriptioncontainerstyle" targettype="dxprg:propertydescriptionpresentercontrol">
    <setter property="showselectedrowheader" value="false" />
    <setter property="minheight" value="70" />
  </style>

  <style targettype="slider">
    <setter property="margin" value="2" />
  </style>
  <style targettype="dxe:comboboxedit">
    <setter property="istexteditable" value="false" />
    <setter property="applyitemtemplatetoselecteditem" value="true" />
    <setter property="margin" value="2" />
  </style>

  <!-- 测试直接从datatemplate获取控件 -->
  <datatemplate x:key="slidertemplate" datatype="local:sliderextend">
    <!--<dxprg:propertydefinition>
      <dxprg:propertydefinition.celltemplate>-->
    <!--<datatemplate>-->
    <stackpanel x:name="root">
      <slider
        maximum="{binding path=max}"
        minimum="{binding path=min}"
        value="{binding path=value}" />
      <textblock text="{binding path=value}" />
    </stackpanel>
    <!--</datatemplate>-->
    <!--</dxprg:propertydefinition.celltemplate>
    </dxprg:propertydefinition>-->
  </datatemplate>

  <datatemplate x:key="comboboxedititemtemplate" datatype="tuple">
    <textblock
      height="20"
      margin="5,3,0,0"
      verticalalignment="center"
      text="{binding item1}" />
  </datatemplate>
</resourcedictionary>

2.编写对应的模板选择类 dynamicallyassigndataeditorstemplateselector:

using devexpress.xpf.editors;
using devexpress.xpf.propertygrid;
using system.componentmodel;
using system.reflection;
using system.windows;
using system.windows.controls;
using system.windows.data;

namespace propertygriddemo.propertygridcontrol
{
  public class dynamicallyassigndataeditorstemplateselector : datatemplateselector
  {
    private propertydescriptor _property = null;
    private rootpropertydefinition _element = null;
    private propertydatacontext _propertydatacontext => app.propertygriddatacontext;

    /// <summary>
    /// 当重写在派生类中,返回根据自定义逻辑的 <see cref="t:system.windows.datatemplate" /> 。
    /// </summary>
    /// <param name="item">数据对象可以选择模板。</param>
    /// <param name="container">数据对象。</param>
    /// <returns>
    /// 返回 <see cref="t:system.windows.datatemplate" /> 或 null。默认值为 null。
    /// </returns>
    public override datatemplate selecttemplate(object item, dependencyobject container)
    {
      _element = (rootpropertydefinition)container;
      datatemplate resource = trycreateresource(item);
      return resource ?? base.selecttemplate(item, container);
    }

    /// <summary>
    /// tries the create resource.
    /// </summary>
    /// <param name="item">the item.</param>
    /// <returns></returns>
    private datatemplate trycreateresource(object item)
    {
      if (!(item is propertydescriptor)) return null;
      propertydescriptor pd = (propertydescriptor)item;
      _property = pd;
      var customuiattribute = (customuiattribute)pd.attributes[typeof(customuiattribute)];
      if (customuiattribute == null) return null;
      var customuitype = customuiattribute.customui;
      return createpropertydefinitiontemplate(customuiattribute);
    }

    /// <summary>
    /// gets the data context.
    /// </summary>
    /// <param name="datacontextpropertyname">name of the data context property.</param>
    /// <returns></returns>
    private object getdatacontext(string datacontextpropertyname)
    {
      propertyinfo property = _propertydatacontext?.gettype().getproperty(datacontextpropertyname);
      if (property == null) return null;
      return property.getvalue(_propertydatacontext, null);
    }

    /// <summary>
    /// creates the slider data template.
    /// </summary>
    /// <param name="customuiattribute">the custom ui attribute.</param>
    /// <returns></returns>
    private datatemplate createsliderdatatemplate(customuiattribute customuiattribute)
    {
      datatemplate ct = new datatemplate();
      ct.visualtree = new frameworkelementfactory(typeof(stackpanel));
      ct.visualtree.setvalue(stackpanel.datacontextproperty, getdatacontext(customuiattribute.datacontextpropertyname));

      frameworkelementfactory sliderfactory = new frameworkelementfactory(typeof(slider));
      sliderfactory.setbinding(slider.maximumproperty, new binding(nameof(slideruidatacontext.max)));
      sliderfactory.setbinding(slider.minimumproperty, new binding(nameof(slideruidatacontext.min)));
      sliderfactory.setbinding(slider.smallchangeproperty, new binding(nameof(slideruidatacontext.smallchange)));
      sliderfactory.setbinding(slider.largechangeproperty, new binding(nameof(slideruidatacontext.largechange)));
      sliderfactory.setbinding(slider.valueproperty, new binding(nameof(slideruidatacontext.value)));
      ct.visualtree.appendchild(sliderfactory);

      frameworkelementfactory textfacotry = new frameworkelementfactory(typeof(textblock), "textblock");
      textfacotry.setvalue(textblock.textproperty, new binding(nameof(slideruidatacontext.value)));
      //textboxfactory.addhandler(textbox.isvisiblechanged, new dependencypropertychangedeventhandler(searchboxvisiblechanged));
      ct.visualtree.appendchild(textfacotry);
      ct.seal();
      return ct;
    }

    /// <summary>
    /// creates the combobox edit template.
    /// </summary>
    /// <param name="customuiattribute">the custom ui attribute.</param>
    /// <returns></returns>
    private datatemplate createcomboboxedittemplate(customuiattribute customuiattribute)
    {
      datatemplate template = new datatemplate();
      template.visualtree = new frameworkelementfactory(typeof(dockpanel));
      template.visualtree.setvalue(dockpanel.datacontextproperty, getdatacontext(customuiattribute.datacontextpropertyname));

      frameworkelementfactory textfactory = new frameworkelementfactory(typeof(textblock)) ;
      textfactory.setvalue(textblock.textproperty, new binding(nameof(comboboxeditdatacontext.name)));
      template.visualtree.appendchild(textfactory);

      frameworkelementfactory comboboxeditfactory = new frameworkelementfactory(typeof(comboboxedit));
      comboboxeditfactory.setbinding(comboboxedit.itemssourceproperty, new binding(nameof(comboboxeditdatacontext.itemsource)));
      comboboxeditfactory.setbinding(comboboxedit.editvalueproperty, new binding(nameof(comboboxeditdatacontext.editvalue)));
      comboboxeditfactory.setbinding(comboboxedit.selectedindexproperty, new binding(nameof(comboboxeditdatacontext.selectedindex)));
      comboboxeditfactory.setvalue(comboboxedit.itemtemplateproperty, (datatemplate)_element.tryfindresource("comboboxedititemtemplate"));
      template.visualtree.appendchild(comboboxeditfactory);
      template.seal();
      return template;
    }

    /// <summary>
    /// creates the property definition template.
    /// </summary>
    /// <param name="customuiattribute">the custom ui attribute.</param>
    /// <returns></returns>
    private datatemplate createpropertydefinitiontemplate(customuiattribute customuiattribute)
    {
      datatemplate datatemplate = new datatemplate();
      datatemplate celltemplate = null;//单元格模板
      frameworkelementfactory factory = new frameworkelementfactory(typeof(propertydefinition));
      datatemplate.visualtree = factory;
      switch (customuiattribute.customui)
      {
        case customuitypes.slider:
          celltemplate = createsliderdatatemplate(customuiattribute); break;
          //celltemplate = (datatemplate)_element.tryfindresource("slidertemplate");break;
        case customuitypes.comboboxeit:
          celltemplate = createcomboboxedittemplate(customuiattribute);break;
        
      }

      if (celltemplate != null)
      {
        factory.setvalue(propertydefinition.celltemplateproperty, celltemplate);
        datatemplate.seal();

      }
      else
      {
        return null;
      }
      return datatemplate;
    }
  }
}
using system.collections.generic;
using system.componentmodel;
using system.linq;

namespace propertygriddemo.propertygridcontrol
{
  /// <summary>
  ///初始化所有属性并调用模板选择器进行匹配
  /// </summary>
  public class dataeditorsviewmodel
  {
    public ienumerable<propertydescriptor> properties { get { return typedescriptor.getproperties(typeof(testpropertygrid)).cast<propertydescriptor>(); } }
  }
}

3.编写一个可用于构建模板的属性 customuitype:

using system;

namespace propertygriddemo.propertygridcontrol
{
  public class customuitype
  {

  }

  public enum customuitypes
  {
    slider,
    comboboxeit,
    spinedit,
    checkboxedit
  }

  [attributeusage(attributetargets.property)]
  internal class customuiattribute : attribute
  {
    public string datacontextpropertyname { get; set; }
    public customuitypes customui { get; set; }
    /// <summary>
    /// 自定义控件属性构造函数
    /// </summary>
    /// <param name="uitypes">the ui types.</param>
    /// <param name="datacontextpropertyname">name of the data context property.</param>
    internal customuiattribute(customuitypes uitypes, string datacontextpropertyname)
    {
      customui = uitypes;
      datacontextpropertyname = datacontextpropertyname;
    }
  }

}

4.编写对应的datacontext类 testpropertygrid:

using devexpress.mvvm.dataannotations;
using system;
using system.componentmodel;
using system.componentmodel.dataannotations;
using system.timers;
using system.windows;

namespace propertygriddemo.propertygridcontrol
{
  [metadatatype(typeof(dynamicallyassigndataeditorsmetadata))]
  public class testpropertygrid : propertydatacontext
  {
    private double _count = 0;
    private slideruidatacontext _countsource = null;
    private comboboxeditdatacontext _combosource = null;
    private double _value=1;

    public testpropertygrid()
    {
      password = "1111111";
      notes = "hello";
      text = "hello hi";
    }

    [browsable(false)]
    public slideruidatacontext countsource
    {
      get
      {
        if (_countsource != null)
        {

          return _countsource;
        }
        else
        {
          _countsource = new slideruidatacontext(0, 100, count, 0.1, 1);
          _countsource.propertychanged += (object o, propertychangedeventargs e) =>
          {
            this.count = _countsource.value;
          };
          return _countsource;
        }
      }
    }

    [browsable(false)]
    public comboboxeditdatacontext combosource
    {
      get
      {
        if(_combosource==null)
        {
          _combosource =new comboboxeditdatacontext(comboboxedititemsource.testitemsource,value);
          _combosource.propertychanged += (object o, propertychangedeventargs e) =>
           {
             this.value =convert.todouble(_combosource.editvalue.item2); 
           };
          
        }
        return _combosource;
      }
    }

    [display(name = "slideredit", groupname = "customui")]
    [customui(customuitypes.slider, nameof(countsource))]
    public double count
    {
      get => _count;
      set
      {
        _count = value;
        countsource.value = value; 
        raisepropertychanged(nameof(count));
      }
    }

    [display(name = "comboboxedititem", groupname = "customui")]
    [customui(customuitypes.comboboxeit, nameof(combosource))]
    public double value
    {
      get => _value;
      set
      {
        if (_value == value) return;
        _value = value;
        //combosource.value = value;
        raisepropertychanged(nameof(value));
      }
    }

    [display(name = "password", groupname = "defaultui")]
    public string password { get; set; }

    [display(name = "textedit", groupname = "defaultui")]
    public string text { get; set; }

    [display(name = "notes", groupname = "defaultui")]
    public string notes { get; set; }


    [display(name = "double", groupname = "defaultui")]
    [defaultvalue(1)]
    public double testdouble { get; set; }

    [display(name = "items", groupname = "defaultui")]
    [defaultvalue(visibility.visible)]
    public visibility testitems { get; set; }
  }

  public static class dynamicallyassigndataeditorsmetadata
  {
    public static void buildmetadata(metadatabuilder<testpropertygrid> builder)
    {
      builder.property(x => x.password)
        .passworddatatype();

      builder.property(x => x.notes)
        .multilinetextdatatype();
    }
  }
}

 该类中用到的其他类主要有以下几个,以下几个类主要用于数据绑定:

 namespace propertygriddemo.propertygridcontrol
{
  public class slideruidatacontext:propertydatacontext
  {
    private double _value = 0;
    private double _max = 0;
    private double _min = 0;
    private double _smallchange = 1;
    private double _largechange=1;

    public slideruidatacontext()
    {

    }

    /// <summary>
    /// initializes a new instance of the <see cref="slideruidatacontext"/> class.
    /// </summary>
    /// <param name="min">the minimum.</param>
    /// <param name="max">the maximum.</param>
    /// <param name="value">the value.</param>
    /// <param name="smallchange">the small change.</param>
    /// <param name="largechange">the large change.</param>
    public slideruidatacontext(double min, double max, double value,double smallchange=0.01,double largechange=0.1)
    {
      smallchange = smallchange;
      largechange = largechange;
      max = max;
      min = min;
      value = value;
    }

    /// <summary>
    /// gets or sets the small change.
    /// </summary>
    /// <value>
    /// the small change.
    /// </value>
    public double smallchange
    {
      get => _smallchange;
      set
      {
        if (value == _min) return;
        _min = value;
        raisepropertychanged(nameof(smallchange));
      }
    }

    /// <summary>
    /// gets or sets the large change.
    /// </summary>
    /// <value>
    /// the large change.
    /// </value>
    public double largechange
    {
      get => _largechange;
      set
      {
        if (value == _largechange) return;
        _largechange = value;
        raisepropertychanged(nameof(largechange));
      }
    }


    /// <summary>
    /// gets or sets the maximum.
    /// </summary>
    /// <value>
    /// the maximum.
    /// </value>
    public double max
    {
      get => _max;
      set
      {
        if (value == _max) return;
        _max = value;
        raisepropertychanged(nameof(max));
      }
    }

    /// <summary>
    /// gets or sets the minimum.
    /// </summary>
    /// <value>
    /// the minimum.
    /// </value>
    public double min
    {
      get => _min;
      set
      {
        if (value == _min) return;
        _min = value;
        raisepropertychanged(nameof(min));
      }
    }

    /// <summary>
    /// gets or sets the value.
    /// </summary>
    /// <value>
    /// the value.
    /// </value>
    public double value
    {
      get => _value;
      set
      {
        if (value == _value) return;
        _value = value;
        raisepropertychanged(nameof(value));
      }
    }
  }
}

using system;
using system.linq;

namespace propertygriddemo.propertygridcontrol
{
  public class comboboxeditdatacontext:propertydatacontext
  {
    private tuple<string, object>[] _itemsource;
    private tuple<string, object> _editvalue;
    private int _selectedindex;

    /// <summary>
    /// initializes a new instance of the <see cref="comboboxeditdatacontext"/> class.
    /// </summary>
    /// <param name="itemsource">the item source.</param>
    /// <param name="editvalue">the edit value.</param>
    public comboboxeditdatacontext(tuple<string,object>[] itemsource,tuple<string,object> editvalue)
    {
      _itemsource = itemsource;
      _editvalue = _itemsource.firstordefault(x => x?.item1.tostring() == editvalue?.item1.tostring() && x?.item2?.tostring() == x?.item2?.tostring());
    }

    /// <summary>
    /// initializes a new instance of the <see cref="comboboxeditdatacontext" /> class.
    /// </summary>
    /// <param name="itemsource">the item source.</param>
    /// <param name="value">the value.</param>
    public comboboxeditdatacontext(tuple<string, object>[] itemsource, object value)
    {
      _itemsource = itemsource;
      _editvalue = _itemsource.firstordefault(x => x?.item2.tostring() == value.tostring() );
    }

    public string name
    {
      get;set;
    }

    /// <summary>
    /// gets or sets the item source.
    /// </summary>
    /// <value>
    /// the item source.
    /// </value>
    public tuple<string,object>[] itemsource
    {
      get => _itemsource;
      set
      {
        //if (_itemsource == value) return;
        _itemsource = value;
        raisepropertychanged(nameof(itemsource));
      }
    }

    /// <summary>
    /// gets or sets the edit value.
    /// </summary>
    /// <value>
    /// the edit value.
    /// </value>
    public tuple<string,object> editvalue
    {
      get => _editvalue;
      set
      {
        if (_editvalue == value) return;
        _editvalue = value;
        raisepropertychanged(nameof(editvalue));
      }
    }

    public object value
    {
      set
      {
        editvalue = itemsource.firstordefault(x => x.item2.equals(value));
      }
    }

    /// <summary>
    /// gets or sets the index of the selected.
    /// </summary>
    /// <value>
    /// the index of the selected.
    /// </value>
    public int selectedindex
    {
      get => _selectedindex;
      set
      {
        if (_selectedindex == value || value==-1) return;
        _selectedindex = value;
        editvalue = itemsource[value];
        raisepropertychanged(nameof(selectedindex));
      }
    }
  }
}
using system.componentmodel;

namespace propertygriddemo.propertygridcontrol
{
  public class propertydatacontext:inotifypropertychanged
  {
    /// <summary>
    /// 在更改属性值时发生。
    /// </summary>
    public event propertychangedeventhandler propertychanged;

    /// <summary>
    /// 触发属性变化
    /// </summary>
    /// <param name="propertyname"></param>
    public virtual void raisepropertychanged(string propertyname)
    {
      propertychanged?.invoke(this, new propertychangedeventargs(propertyname));
    }
  }
}

using system;

namespace propertygriddemo.propertygridcontrol
{
  internal static class comboboxedititemsource
  {
    internal static tuple<string, object>[] testitemsource = new tuple<string, object>[] {
      new tuple<string, object>("1",1),
      new tuple<string, object>("2",2),
      new tuple<string, object>("3",3)
    };
  }
}

5.将以上的custompropertygrid丢进容器中即可,这里我直接用mainwindow来演示:

<window
  x:class="propertygriddemo.mainwindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:propertygridcontrol="clr-namespace:propertygriddemo.propertygridcontrol"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:local="clr-namespace:propertygriddemo"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  title="mainwindow"
  width="525"
  height="350"
  windowstate="maximized"
  mc:ignorable="d">
  <grid margin="10">
    <grid.columndefinitions>
      <columndefinition width="259*" />
      <columndefinition width="259*" />
    </grid.columndefinitions>

    <textbox
      x:name="outputbox"
      grid.columnspan="1"
      horizontalscrollbarvisibility="auto"
      scrollviewer.cancontentscroll="true" />
    <propertygridcontrol:custompropertygrid x:name="propertygrid" grid.column="1" />
  </grid>
</window>

运行示意图:

PropertyGrid自定义控件使用详解

以上就是自定义propertygrid控件的实现代码,本人只实现了简单的slider和comboboxedit控件,实际上可以根据自己的需要仿照以上的方法扩展到其他控件,这个就看需求了。

个人感觉以上方案还是有所欠缺,主要是自定义控件的模板是由代码生成的,如果可以直接从资源文件中读取将会更加方便,不过本人尝试了几次并不能成功的实现数据的绑定,如果大家有什么好的解决方案欢迎在评论区留言,也欢迎大家在评论区进行讨论。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。