最好将模板存储在资源中:
<Window.Resources>
<DataTemplate x:Key="DefaultTemplate">
<Grid x:Name="GridItem" Width="200">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock x:Name="Parameter" Grid.Column="1" Text="{Binding Path=Name}" Margin="5,1,0,0" />
<TextBlock x:Name="Value" Grid.Column="2" Text="{Binding Path=Age}" Margin="85,1,0,0" />
<Line x:Name="Separator" X1="0" X2="0" Y1="0" Y2="20" SnapsToDevicePixels="True" Grid.Column="1" Stroke="Black" StrokeThickness="2" Margin="50,0,0,0" HorizontalAlignment="Left" />
</Grid>
</DataTemplate>
</Window.Resources>
列表框定义:
<ListBox Name="MyListBox" ItemTemplate="{StaticResource DefaultTemplate}" />
在代码 C# 中:
public class Person
{
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
}
定义 ObservableCollection:
private ObservableCollection<Person> MyListBoxData = new ObservableCollection<Person>();
并在集合中添加项目:
MyListBoxData.Add(new Person()
{
Name = "Nick",
Age = 21,
});
MyListBoxData.Add(new Person()
{
Name = "Adam",
Age = 11,
});
MyListBox.ItemsSource = MyListBoxData;
编辑:
然后设置第一个TextBlock的Width="3*"、Width="*"和Margin="-WidthGrid":
<Grid x:Name="GridItem" Width="300">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock x:Name="Parameter" Grid.Column="1" Text="{Binding Path=Name}" Margin="-220,0,0,0" />
<TextBlock x:Name="Value" Grid.Column="2" Text="{Binding Path=Age}" Margin="0,0,0,0" />
</Grid>