首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UWP DataGridComboBoxColumn变换器

UWP DataGridComboBoxColumn变换器
EN

Stack Overflow用户
提问于 2022-03-14 16:57:03
回答 1查看 73关注 0票数 1

我正在尝试使用动态创建的显示枚举选项的DataGridComboBoxColumn列来创建UWP数据集,但是使用自定义的组合框标签。要做到这一点,我必须:

代码语言:javascript
复制
List<EnumDisplay> enums = new List<EnumDisplay>();
EnumConverter converter = new EnumConverter(propertyInfo.PropertyType);
foreach (var kv in converter.Labels)
{
    enums.Add(new EnumDisplay { DisplayName = kv.Key, Value = kv.Value as Enum });
}
Binding binding = new Binding
{
    Path = new PropertyPath(*name of property relevant to this column*),
    Mode = BindingMode.TwoWay,
    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
    Converter = converter
};
DataGridComboBoxColumn col = new DataGridComboBoxColumn()
{                                                 
    ItemsSource = enums
    DisplayMemberPath = nameof(EnumDisplay.DisplayName),
    Binding = binding
};

若要创建列,请使用以下类:

代码语言:javascript
复制
internal class EnumDisplay
{
    public Enum Value { get; set; }
    public string DisplayName { get; set; }
}

public class EnumConverter : IValueConverter
{
    public Dictionary<string, object> Labels { get; } = new Dictionary<string, object>();
    internal EnumConverter(Type enumType)
    {
        // Make a dictionary of label names for each value in the enum
        foreach (object value in enumType.GetEnumValues())
        {
            // This static method converts the enum value to the desired string
            string label = Extensions.EnumValueToLabel(enumType, value);
            Labels.Add(label, value);
        }
    }

    public object Convert(object value, Type targetType, object parameter, string language)
    {
        // Lookup the key from the value
        return Labels.FirstOrDefault(x => x.Value.ToString() == value.ToString()).Key;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        // Lookup the value from the key
        return Labels[value.ToString()];
    }
}

但是,这会产生错误:*System.ArgumentException:‘ItemsSource元素不包含与此列相关的属性的属性名。请确保绑定路径已被正确设置。’*

我不明白为什么绑定所使用的属性的名称应该应用于组合框的ItemSource。我遗漏了什么?

提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-15 04:11:10

*System.ArgumentException:“ItemsSource元素不包含与此列相关的属性的属性名称。请确保绑定路径已被正确设置。”*

我可以重现您的问题,它看起来绑定上下文错误,因为这个问题,请免费报告这个问题在社区工具包github。目前,我们有一个解决办法,使用字符串列表来替换项目列表,比如正式的正在处理中。另一种方法是设置绑定EnumDisplay属性,与DataGrid项一个属性相同。

例如,如果DataGrid项模型包含一个名为Description的属性,则需要为EnumDisplay设置相同的属性名。它将解决上述异常,但默认的DataGridComboBoxColumn单元格内容将为null。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71471480

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档