我有一个名为Track的课程:
public class Track
{
public string Title { get; set; }
public List<Artist> Artists { get; set; }
}
此类包含Artist对象列表:
public class Artist
{
public string Name { get; set; }
}
现在我想将它绑定到WPF中的GridView:
<ListView x:Name="TracksList" Margin="37,325,33,0" VerticalAlignment="Top" Grid.ColumnSpan="1" MouseDoubleClick="TrackList_MouseDoubleClick" Foreground="#FFDEDEDE" Background="#FF232323">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Title}" Width="400px" Header="Titel" />
<GridViewColumn DisplayMemberBinding="{Binding Artists}" Width="200px" Header="Artists" />
</GridView>
</ListView.View>
</ListView>
我使用Track对象列表来填充这个GridView:
TracksList.ItemsSource = album.TrackCollection;
我想要实现的是在Artists列中显示包含所有艺术家姓名的字符串(例如“Artist 1,Artist 2,Artist 3”)。我得到的是一个字符串,解释该字段包含一个列表。我明白为什么会得到这个结果:我没有告诉绑定如何解析和显示列表。
如何配置绑定,以便在列字段中显示艺术家列表。
答案 0 :(得分:2)
你可以使用这样的Binding.Converter:
class ArtistsListConverter : IValueConverter
{
public object Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
object result = null;
var artists = value as IEnumerable<Artist>;
if (artists != null)
{
result = string.Join(", ", artists.Select(a => a.Name));
}
return result;
}
public object ConvertBack(
object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
XAML:
<local:ArtistsListConverter x:Key="ArtistsListConverter"/>
...
DisplayMemberBinding="{Binding Artists,
Converter={StaticResource ArtistsListConverter}}"
答案 1 :(得分:1)
这就是视图模型的原因:
public class TrackViewModel
{
public TrackViewModel(Track model)
{
Title = model.Title;
Artists = string.Join(", ", model.Artists.Select(a => a.Name));
}
public string Title { get; private set; }
public string Artists { get; private set; }
}
答案 2 :(得分:1)
如果你绑定了艺术家列表,转换器实际上只是那个。所以,这是转换器的略微即兴版本。
public class ArtistsToStringConverter : System.Windows.Data.IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var artists = value as IEnumerable<Artist>;
if (artists != null)
{
var artistNames = from artist in artists select artist.Name;
return string.Join(", ", artistNames);
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}