我有以下XAML代码:
<Window x:Class="SourcicoProjectTest.RecipeListWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SourcicoProjectTest.code"
mc:Ignorable="d"
Title="RecipeListWindow" Height="450" Width="800" Loaded="Window_Loaded">
<Window.DataContext>
<local:MainMVVM/>
</Window.DataContext>
<Window.Resources>
<local:RecipeCountConverter x:Key="countConverter"/>
</Window.Resources>
<Grid>
<DataGrid Margin="5, 5, 5, 5"
SelectedItem="{Binding selectedRecipe}"
ItemsSource="{Binding recipesList}"
IsReadOnly="True"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Recipe ID"
Binding="{Binding ID}" />
<DataGridTextColumn Header="Recipe Name"
Binding="{Binding name}" />
<DataGridTextColumn Header="Recipe Source"
Binding="{Binding source}" />
<DataGridTextColumn Header="Num. of Ingredients"
Binding="{Binding Path=ingredients.Count}" />
<DataGridTextColumn Header="Ingredients"
Binding="{Binding Path=ingredients}" />
<DataGridTextColumn Header="Prep. Time"
Binding="{Binding prepTime}" />
<DataGridTextColumn Header="Prep. Instructions"
Binding="{Binding prepInstructions}" />
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="Details"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="Delete"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
所选项目的类型为配方。食谱有成分清单:
ObservableCollection<Ingredient> ingredients
我只想显示前三个成分(用逗号分隔),如果单列中包含三个以上,则添加省略号(...)。
<DataGridTextColumn Header="Ingredients"
Binding="{Binding Path=ingredients}" />
我应该在我的XAML代码中做什么???
答案 0 :(得分:1)
有几种方法可以做到这一点。我会亲自使用转换器。像这样:
class IngredientsListToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var list = value as IEnumerable<string>;
if (list == null)
return String.Empty;
var output = String.Join(", ", list.Take(3));
if (list.Count > 3)
output += "...";
return output;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
添加转换器,就像您已经添加了RecipeCountConverter
一样,然后将其添加到绑定中,如下所示:
<DataGridTextColumn Header="Ingredients"
Binding="{Binding Path=ingredients, Converter={StaticResource IngredientsListToStringConverter}" />