【问题标题】:Cant bind a property as enum to combobox in wpf mvvm无法将属性作为枚举绑定到 wpf mvvm 中的组合框
【发布时间】:2018-01-12 22:28:45
【问题描述】:

我有以下场景:

问题:无法将属性作为枚举绑定到 wpf mvvm 中的组合框?

如何将此枚举绑定到组合框?

1.我有一个枚举。

public enum RankType
{
   StringValue1,
   StringValue2,
   StringValue3
} 

2.我在 myclass 中有一个属性作为枚举:

[DefaultValue(RankType.StringValue1)]
[ConvertUsing(typeof(EnumTypeConverter<RankType>))]
public RankType Rank { set; get; }

ConvertUsing Class,它为我做转换:

[System.AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class ConvertUsingAttribute:Attribute
{
    private TypeConverter _converter = null;
    public TypeConverter Converter
    {
        get
        {
            if (_converter == null)
                _converter = (TypeConverter)System.Activator.CreateInstance(TypeOfConverter);
            return _converter;
        }
    }
    public Type TypeOfConverter
    {
        get;
        private set;
    }
    public ConvertUsingAttribute(Type converterType)
    {
        this.TypeOfConverter = converterType;
    }
}

EnumTypeConverter 类:

public class EnumTypeConverter<T>:TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return sourceType == typeof(string);
    }
    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        return destinationType == typeof(string);
    }
    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
    {
        if (value != null && value is string)
        {
            return Enum.Parse(typeof(T), (string)value);// int.Parse(((string)value).Trim());
        }
        return base.ConvertFrom(context, culture, value);
    }
    public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
    {
        if (value != null && destinationType == typeof(string))
        {
            return ((T)value).ToString();
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }
}

4.在视图模型中

private MilitaryRankType _selectedRankType;

public RankType SelectedRankType 
{  
        get { return _selectedRankType; }
        set
        {
            _selectedRankType = value;
            NotifyPropertyChanged(nameof(RankTypes));
        } 
}

private RankType[] _rankTypes;
public RankType[] RankTypes
{
    get
    {
       return _rankTypes ??
              (_rankTypes =Enum.GetValues(typeof(RankType)).Cast<RankType>().ToArray());
    }
}

5.在视图中

<ComboBox ItemsSource="{Binding RankTypes, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}" SelectedItem="{Binding SelectedRankType}" />

6.我在xaml中使用了listview

   <ListView ItemsSource="{Binding EmployeesList}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="3">
                        <ListView.View>
                            <GridView>
                                <GridViewColumn Width="150" Header="">
                                    <GridViewColumn.CellTemplate>
                                        <DataTemplate>
                                            <TextBox Text="{Binding Path=NationalId, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}" />
                                        </DataTemplate>
                                    </GridViewColumn.CellTemplate>
                                </GridViewColumn>
                                <GridViewColumn Width="150" Header="">
                                    <GridViewColumn.CellTemplate>
                                        <DataTemplate>
                                            <TextBox Text="{Binding Path=CardId, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}" />
                                        </DataTemplate>
                                    </GridViewColumn.CellTemplate>
                                </GridViewColumn>

                                <GridViewColumn Width="150" Header="">
                                    <GridViewColumn.CellTemplate>
                                        <DataTemplate>
                                            **<ComboBox SelectedItem="{Binding SelectedRankType}" />**
                                        </DataTemplate>
                                    </GridViewColumn.CellTemplate>
                                </GridViewColumn>

                                <GridViewColumn Width="150" Header="">
                                    <GridViewColumn.CellTemplate>
                                        <DataTemplate>
                                            <TextBox Text="{Binding Path=FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}" />
                                        </DataTemplate>
                                    </GridViewColumn.CellTemplate>
                                </GridViewColumn>
                                <GridViewColumn Width="150" Header="">
                                    <GridViewColumn.CellTemplate>
                                        <DataTemplate>
                                            <TextBox Text="{Binding Path=LastName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,NotifyOnValidationError=True,ValidatesOnDataErrors=True,ValidatesOnExceptions=True}"/>
                                        </DataTemplate>
                                    </GridViewColumn.CellTemplate>
                                </GridViewColumn>

                            </GridView>
                        </ListView.View>
                    </ListView>

【问题讨论】:

  • 为什么至少没有实现 INotifyPropertyChanged?
  • ItemsSource 上的 UpdateSourceTrigger=PropertyChanged 没有任何意义。 TwoWay 属性必须是SelectedItem。您对在似乎不直接参与整个组合框绑定的 public RankType Rank { set; get; } 属性进行注释有什么期望?
  • 请添加更多关于预期和实际行为的详细信息。即使没有任何 TypeConverter 的东西,这也应该没有问题,我只是无法重现你遇到的任何问题。
  • 在 BaseEntity 类中实现 INotifyPropertyChanged
  • 我的目的是将枚举绑定到组合框。使用注释将枚举转换为视图中的组合框数据

标签: wpf mvvm data-binding combobox enums


【解决方案1】:

老实说,我真的不知道你的代码出了什么问题,但我可以给你一个没有任何花哨转换器的工作示例:

假设您有以下窗口内容:

<Grid x:Name="grid1">
    <ComboBox ItemsSource="{Binding SelectableRanks}" SelectedItem="{Binding SelectedRank}"/>
</Grid>

然后你在窗口构造函数中初始化数据上下文:

public MainWindow()
{
    InitializeComponent();
    grid1.DataContext = new RankSelectionVM();
}

这是你的视图模型:

public class RankSelectionVM
{
    private RankType _SelectedRank;
    public RankType SelectedRank
    {
        get { return _SelectedRank; }
        set { _SelectedRank = value; }
    }

    private RankType[] _rankTypes;
    public RankType[] SelectableRanks
    {
        get
        {
            return _rankTypes ??
                   (_rankTypes = Enum.GetValues(typeof(RankType)).Cast<RankType>().ToArray());
        }
    }
}

public enum RankType
{
    StringValue1,
    StringValue2,
    StringValue3
}

它没有任何INotifyPropertyChanged 或任何附加的转换器,但在SelectedRank 设置器中放置一个断点 - 当您选择一个值时它应该会中断。如果此代码对您有用,您必须找出您所做的不同之处才能在您的项目中获得一个不工作的代码。否则你可能会遇到一些非常奇怪的问题需要特别注意。

【讨论】:

  • 当ComboBox在ListView里面时不起作用,但是当Combobox不在ListView里面时,如何使用祖先?对于我的 ViewModel?
  • @4mir 您的问题中没有ListView,如果您有此类问题,请更新您的问题。另外,看看Visual Studio的输出窗口,如果你的绑定错误,它应该会显示一些绑定错误。
  • @4mir 现在您根本没有任何枚举ItemsSource,没有关于包含EmployeesList 的视图模型的信息,(4.) 中的类型彼此不匹配还有一大堆其他属性绑定对您的问题的读者来说仍然是个谜。请尝试以一致的方式提供您的信息,就像现在一样,它只是令人困惑。
  • 对于 ItemSource 测试但不起作用!
  • 解决方案:&lt;ComboBox ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ListView},Path=DataContext.RankTypes}" SelectedItem="{Binding Rank}" /&gt;
猜你喜欢
  • 2015-08-20
  • 2010-09-08
  • 1970-01-01
  • 1970-01-01
  • 2016-02-06
  • 2018-11-12
  • 2020-02-07
  • 1970-01-01
相关资源
最近更新 更多