绑定 Silverlight 组合框不显示 EnumBinder 的默认值

发布于 2024-12-05 16:40:03 字数 4979 浏览 1 评论 0原文

我的模型使用枚举来固定多个选择。我正在使用 Dean Chalk 的 EnumBinder,位于 http://deanchalk.me .uk/post/Enumeration-Binding-In-Silverlight.aspx ,绑定到组合框。除了未显示默认值之外,一切似乎都运行良好。选定的索引是-1,我绑定到SelectedItem还是SelectedValue都没关系。否则组合框工作正常。我对任何其他绑定组合框的默认值都没有问题。

enumbindingsupport.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;

/* All of this was once just part of the RichClient sub-namespace
 * but it has its uses elsewhere, so it has been moved. 
 */

/// <summary>
/// Container for enumeration values.
/// </summary>
/// <remarks>
/// http://deanchalk.me.uk/post/Enumeration-Binding-In-Silverlight.aspx
/// </remarks>
public sealed class EnumContainer
{
    public int EnumValue { get; set; }
    public string EnumDescription { get; set; }
    public object EnumOriginalValue { get; set; }
    public override string ToString() {
        return EnumDescription;
    }

    public override bool Equals(object obj) {
        if (obj == null)
            return false;
        if (obj is EnumContainer)
            return EnumValue.Equals((int)((EnumContainer)obj).EnumValue);
        return EnumValue.Equals((int)obj);
    }

    public override int GetHashCode() {
        return EnumValue.GetHashCode();
    }

}

/// <summary>
/// A collection to store a list of EnumContainers that hold enum values.
/// </summary>
/// <remarks>
/// http://deanchalk.me.uk/post/Enumeration-Binding-In-Silverlight.aspx
/// </remarks>
/// <typeparam name="T"></typeparam>
public class EnumCollection<T> : List<EnumContainer> where T : struct
{
    public EnumCollection() {
        var type = typeof(T);
        if (!type.IsEnum)
            throw new ArgumentException("This class only supports Enum types");
        var fields = typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public);
        foreach (var field in fields) {
            var container = new EnumContainer();
            container.EnumOriginalValue = field.GetValue(null);
            container.EnumValue = (int)field.GetValue(null);
            container.EnumDescription = field.Name;
            var atts = field.GetCustomAttributes(false);
            foreach (var att in atts)
                if (att is DescriptionAttribute) {
                    container.EnumDescription = ((DescriptionAttribute)att).Description;
                    break;
                }
            Add(container);
        }

    }
}

enumvalueconverter.cs

using System;
using System.Globalization;
using System.Windows.Data;

/// <summary>
/// Supports two-way binding of enumerations.
/// </summary>
public class EnumValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,
                            CultureInfo culture) {
        return (int)value;
    }

    public object ConvertBack(object value, Type targetType, object parameter,
                            CultureInfo culture) {
        if (value == null)
            return null;
        if (value.GetType() == targetType)
            return value;
        return ((EnumContainer)value).EnumOriginalValue;
    }
}

使用的枚举:

/// <summary>
/// Describes the available sorting options.
/// </summary>
public enum PeopleSortOptionsEnum
{

    [Display(Order = 10)]
    [Description("First Name, Last Name")]
    FirstNameThenLastName,

    [Display(Order = 20)]
    [Description("Last Name, First Name")]
    LastNameThenFirstName,

    [Display(Order = 30)]
    Grade,

    [Display(Order = 40)]
    Gender,

    [Display(Order = 50)]
    Age
}

我的模型上的属性:

    /// <summary>
    /// This is the list for the enumeration to bind to.
    /// </summary>
    public EnumCollection<PeopleSortOptionsEnum> AvailableSortOptions
    {
        get { return new EnumCollection<PeopleSortOptionsEnum>(); }
    }

XAML 代码片段:

    <ComboBox ItemsSource="{Binding Path=AvailableSortOptions, Mode=OneWay}" SelectedValue="{Binding Path=Preferences.SortOrder, Mode=TwoWay, Converter={StaticResource EnumConverter}}" Grid.Column="1" Grid.Row="2" Height="32" Margin="48,31,0,0" x:Name="cboSort" VerticalAlignment="Top" />

其中 Preferences.SortOrder 的类型为 PeopleSortOptionsEnum,转换器在我的 app.xaml 中作为所有枚举类型的转换器。

任何人都知道为什么它不会将索引设置为当前选定的值?我正要在代码隐藏中添加一些代码,以将 selectedindex 设置为加载时当前选定的值,但一想到它我就觉得很肮脏。

除了这个问题之外,它运行得非常好,所以感谢 Dean!

编辑 添加 Preferences.SortOrder 代码:

public PeopleSortOptionsEnum SortOrder 
{ 
  get { return sortOrder; } 
  set 
  { 
    if (sortOrder != value) 
    { 
      sortOrder = value; 
      PropertyHasChanged("SortOrder"); 
    } 
  } 
}

My models use enums for fixed multiple selections. I'm using Dean Chalk's EnumBinder, found at http://deanchalk.me.uk/post/Enumeration-Binding-In-Silverlight.aspx , to bind to a combo box. Everything seems to work great except the default value isn't shown. The selected index is -1, and it doesn't matter if I bind to SelectedItem or SelectedValue. The combobox works fine otherwise. I have no problems with default values with any other bound comboboxes.

enumbindingsupport.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;

/* All of this was once just part of the RichClient sub-namespace
 * but it has its uses elsewhere, so it has been moved. 
 */

/// <summary>
/// Container for enumeration values.
/// </summary>
/// <remarks>
/// http://deanchalk.me.uk/post/Enumeration-Binding-In-Silverlight.aspx
/// </remarks>
public sealed class EnumContainer
{
    public int EnumValue { get; set; }
    public string EnumDescription { get; set; }
    public object EnumOriginalValue { get; set; }
    public override string ToString() {
        return EnumDescription;
    }

    public override bool Equals(object obj) {
        if (obj == null)
            return false;
        if (obj is EnumContainer)
            return EnumValue.Equals((int)((EnumContainer)obj).EnumValue);
        return EnumValue.Equals((int)obj);
    }

    public override int GetHashCode() {
        return EnumValue.GetHashCode();
    }

}

/// <summary>
/// A collection to store a list of EnumContainers that hold enum values.
/// </summary>
/// <remarks>
/// http://deanchalk.me.uk/post/Enumeration-Binding-In-Silverlight.aspx
/// </remarks>
/// <typeparam name="T"></typeparam>
public class EnumCollection<T> : List<EnumContainer> where T : struct
{
    public EnumCollection() {
        var type = typeof(T);
        if (!type.IsEnum)
            throw new ArgumentException("This class only supports Enum types");
        var fields = typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public);
        foreach (var field in fields) {
            var container = new EnumContainer();
            container.EnumOriginalValue = field.GetValue(null);
            container.EnumValue = (int)field.GetValue(null);
            container.EnumDescription = field.Name;
            var atts = field.GetCustomAttributes(false);
            foreach (var att in atts)
                if (att is DescriptionAttribute) {
                    container.EnumDescription = ((DescriptionAttribute)att).Description;
                    break;
                }
            Add(container);
        }

    }
}

enumvalueconverter.cs

using System;
using System.Globalization;
using System.Windows.Data;

/// <summary>
/// Supports two-way binding of enumerations.
/// </summary>
public class EnumValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,
                            CultureInfo culture) {
        return (int)value;
    }

    public object ConvertBack(object value, Type targetType, object parameter,
                            CultureInfo culture) {
        if (value == null)
            return null;
        if (value.GetType() == targetType)
            return value;
        return ((EnumContainer)value).EnumOriginalValue;
    }
}

enum used:

/// <summary>
/// Describes the available sorting options.
/// </summary>
public enum PeopleSortOptionsEnum
{

    [Display(Order = 10)]
    [Description("First Name, Last Name")]
    FirstNameThenLastName,

    [Display(Order = 20)]
    [Description("Last Name, First Name")]
    LastNameThenFirstName,

    [Display(Order = 30)]
    Grade,

    [Display(Order = 40)]
    Gender,

    [Display(Order = 50)]
    Age
}

property on my model:

    /// <summary>
    /// This is the list for the enumeration to bind to.
    /// </summary>
    public EnumCollection<PeopleSortOptionsEnum> AvailableSortOptions
    {
        get { return new EnumCollection<PeopleSortOptionsEnum>(); }
    }

XAML snippet:

    <ComboBox ItemsSource="{Binding Path=AvailableSortOptions, Mode=OneWay}" SelectedValue="{Binding Path=Preferences.SortOrder, Mode=TwoWay, Converter={StaticResource EnumConverter}}" Grid.Column="1" Grid.Row="2" Height="32" Margin="48,31,0,0" x:Name="cboSort" VerticalAlignment="Top" />

Where Preferences.SortOrder is of type PeopleSortOptionsEnum, the converter is in my app.xaml as a converter for all enum types.

Anyone have any idea why it won't set the index to the currently selected value? I'm about to just throw some code in the codebehind to set the selectedindex to the currently selected value on load, but I feel so dirty just thinking about it.

Besides this issue, it works wonderfully, so thanks Dean!

Edit Adding the Preferences.SortOrder code:

public PeopleSortOptionsEnum SortOrder 
{ 
  get { return sortOrder; } 
  set 
  { 
    if (sortOrder != value) 
    { 
      sortOrder = value; 
      PropertyHasChanged("SortOrder"); 
    } 
  } 
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一城柳絮吹成雪 2024-12-12 16:40:03

问题是枚举转换器类上的 Convert 方法:

public object Convert(object value, Type targetType, object parameter,
                        CultureInfo culture) {
    return (int)value;
}

当组合框 SelectedItem 从 SortOrder 获取值时,它会以枚举值返回,该转换器将其转换为 int。但是,组合框项是 EnumContainer 对象的集合,而不是整数。所以无法设置所选项目。

要解决该问题,您必须做两件事。首先更改组合框绑定并设置 SelectedValuePath:

<ComboBox ItemsSource="{Binding Path=AvailableSortOptions}" 
          SelectedValue="{Binding Path=SortOrder, Mode=TwoWay, Converter={StaticResource EnumConverter}}" 
          SelectedValuePath="EnumOriginalValue"/>

其次,您必须稍微修改转换器上的 Convert 方法:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
  return value;
}

一旦我进行了这两项更改,它就开始按预期工作。

The issue is the Convert method on your enum converter class:

public object Convert(object value, Type targetType, object parameter,
                        CultureInfo culture) {
    return (int)value;
}

When the combobox SelectedItem is gets the value from SortOrder it is return in Enum value which this converter is converting to an int. However, the combobox items is a collection of EnumContainer objects, not ints. So it fails to set the selected item.

To resolve the issue you have to do two things. First change your combobox bindings and set the SelectedValuePath:

<ComboBox ItemsSource="{Binding Path=AvailableSortOptions}" 
          SelectedValue="{Binding Path=SortOrder, Mode=TwoWay, Converter={StaticResource EnumConverter}}" 
          SelectedValuePath="EnumOriginalValue"/>

Second you have to slightly modify the Convert method on your converter:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
  return value;
}

Once I made those two changes it started working as expected.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文