WPF DataGridComboBox绑定enum

定义Enum

public enum Types
    {
        不变, 随机, 波动
    }

前台代码

<Window.Resources>
        <ObjectDataProvider x:Key="myEnum" MethodName="GetValues" ObjectType="{x:Type core:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type Type="local:Types"/>
            ObjectDataProvider.MethodParameters>
        ObjectDataProvider>
    Window.Resources>
<DataGrid Name="dg_render"  Margin="0,20,20,0" MinWidth="250px" CanUserAddRows="False" ItemsSource="{Binding}" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    
                    <DataGridComboBoxColumn Header="类型" SelectedValueBinding="{Binding Type}" ItemsSource="{Binding Source={StaticResource myEnum}}">                 
                    DataGridComboBoxColumn>
                DataGrid.Columns>
            DataGrid>

注意将Type类的命名空间引入到xaml中。

后台数据绑定

  1. 绑定DataGrid
ocr = new ObservableCollection();
...
this.dg_render.ItemsSource = ocr;
  1. 编写RenderHelper类
class RenderHelper: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private Types type;
public Types Type
        {
            get
            {
                return type;
            }

            set
            {
                type = value;
                if (this.PropertyChanged != null)
                {
                    this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Type"));
                }
            }
        }
        ...
}

运行效果

WPF DataGridComboBox绑定enum_第1张图片

你可能感兴趣的:(C#)