【发布时间】:2012-10-07 01:47:16
【问题描述】:
长话短说,我的应用程序的一部分包含一系列绑定到 Xaml 中的对象实例的列表框。使用IValueConverter,我能够从主对象中检索<Part> 对象列表并显示检索到的对象的.ToString() 形式。但是,我想做的是显示对象的 Name 属性。我将DisplayMemberPath 设置为Name,但结果仅将listboxitem 置空。我已经在下面发布了代码的相关部分:
XAML:
<Window.Resources>
<local:LocationtoEquipmentCOnverter x:Key="locationEquipmentFiller" />
</Window.Resources>
<Window.DataContext>
<local:MegaWdiget/>
</Window.DataContext>
<ListBox x:Name="listboxFront" HorizontalAlignment="Left" Margin="180,45,0,0" VerticalAlignment="Top" Width="82" Opacity="0.5" ItemsSource="{Binding ConverterParameter=Front, Converter={StaticResource locationEquipmentFiller}, Mode=OneWay}" DisplayMemberPath="Name"/>
值转换器:
public class LocationtoEquipmentCOnverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
MegaWidget MWidget = (MegaWidget)value;
Location loc = MWidget.Locations[(string)parameter];
return loc.Contents;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
MegaWidget 对象包含以下内容:
[XmlElement]
public Dictionary<string, Location> Locations { get; set; }
位置对象包含一个列表,其中包含我需要查询其名称的实际对象:
public List<Part> Contents;
找到解决方案
按照 Mate 推荐的故障排除路线继续进行后,我发现传递的对象是 Part 对象而不是 ListBoxItems。这导致ListBox 被实际对象而不是ListBoxItems 填充。通过更改 ValueConverter 以传递 ListBoxItems 的 List 并将内容标记设置为我需要的内容,ListBoxes 可以正确填充。我在下面的问题区域中列出了解决方案:
【问题讨论】:
-
如果调试LocationtoEquipmentCONverter方法,参数和答案是否正确? ConverterParameter=Front 可以转换成字符串吗?
-
它确实返回了一个列表(在这种情况下是单个对象),其中包含所有需要的属性。如果我不添加 displaymemberpath,该对象甚至会显示在列表框中,但会显示继承 (system.MWidget.Part) 而不是公共字符串 Name 属性。
标签: c# wpf data-binding listboxitem ivalueconverter