我正在尝试使用动态创建的显示枚举选项的DataGridComboBoxColumn列来创建UWP数据集,但是使用自定义的组合框标签。要做到这一点,我必须:
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
};若要创建列,请使用以下类:
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。我遗漏了什么?
提前谢谢。
发布于 2022-03-15 04:11:10
*System.ArgumentException:“ItemsSource元素不包含与此列相关的属性的属性名称。请确保绑定路径已被正确设置。”*
我可以重现您的问题,它看起来绑定上下文错误,因为这个问题,请免费报告这个问题在社区工具包github。目前,我们有一个解决办法,使用字符串列表来替换项目列表,比如正式的正在处理中。另一种方法是设置绑定EnumDisplay属性,与DataGrid项一个属性相同。
例如,如果DataGrid项模型包含一个名为Description的属性,则需要为EnumDisplay设置相同的属性名。它将解决上述异常,但默认的DataGridComboBoxColumn单元格内容将为null。
https://stackoverflow.com/questions/71471480
复制相似问题