WPF ListBox利用DataTemplate数据绑定后,只显示一行,没有显示多行
叶晨- 2020-07-27 11:47:36 XAML代码:
<Window x:Class="WPF_125P.MainWindow"
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:WPF_125P"
mc:Ignorable="d"
Title="Date Converter" Height="266" Width="300">
<Window.Resources>
<!--以资源的形式创建两个实例-->
<local:CategoryToSourceConverter x:Key="cts"/>
<local:StateToNullableBoolConverter x:Key="stnb"/>
</Window.Resources>
<Grid>
<StackPanel Background="LightBlue">
<ListBox x:Name="listBoxPlane" Height="160" Margin="5" Background="White">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<!--<Image Width="20" Height="20"
Source="{Binding Path=category,Converter={StaticResource cts}}"/>-->
<TextBlock Text="{Binding Path=Name}" Width="60" Height="80,0"/>
<TextBlock Text="{Binding Path=Name}" Width="60" Height="80,0"/>
<!--<CheckBox IsThreeState="True"
IsChecked="{Binding Path=state,Converter={StaticResource stnb}}"/>-->
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button x:Name="buttonLoad" Content="Load" Height="25" Margin="5,0"
Click="buttonLoad_Click"/>
<Button x:Name="buttonSave" Content="Save" Height="25" Margin="5"
Click="buttonSave_Click"/>
</StackPanel>
<!--<Image Source="Icons\Bomber.png" Width="200" Height="200"/>-->
</Grid>
</Window>
C#关键代码:
private void buttonLoad_Click(object sender, RoutedEventArgs e)
{
List<Plane> planes = new List<Plane>()
{
new Plane(){category=Category.Fighter,Name="B-1",state=State.Unknown},
new Plane(){category=Category.Bomber,Name="B-2",state=State.Unknown},
new Plane(){category=Category.Fighter,Name="F-22",state=State.Unknown},
new Plane(){category=Category.Fighter,Name="Su-47",state=State.Unknown},
new Plane(){category=Category.Bomber,Name="B-52",state=State.Unknown},
new Plane(){category=Category.Fighter,Name="J-10",state=State.Unknown},
};
this.listBoxPlane.ItemsSource = planes;
}