在WPF中,要正确绑定ListBoxItem,您需要遵循以下步骤:
public class Item
{
public string Name { get; set; }
public string Description { get; set; }
}
public ObservableCollection<Item> Items { get; set; }
<ListBox ItemsSource="{Binding Items}">
<DataTemplate DataType="{x:Type local:Item}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" />
<TextBlock Text="{Binding Description}" />
</StackPanel>
</DataTemplate>
<ListBox ItemsSource="{Binding Items}" ItemTemplate="{StaticResource ItemTemplate}">
现在,您已经正确绑定了ListBoxItem,并且可以在ListBox中显示数据。
以下是完整的示例代码:
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:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<DataTemplate DataType="{x:Type local:Item}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" />
<TextBlock Text="{Binding Description}" />
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox ItemsSource="{Binding Items}" ItemTemplate="{StaticResource ItemTemplate}">
</ListBox>
</Grid>
</Window>
using System.Collections.ObjectModel;
using System.Windows;
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
}
public class ViewModel
{
public ObservableCollection<Item> Items { get; set; }
public ViewModel()
{
Items = new ObservableCollection<Item>
{
new Item { Name = "Item 1", Description = "Description 1" },
new Item { Name = "Item 2", Description = "Description 2" },
new Item { Name = "Item 3", Description = "Description 3" }
};
}
}
public class Item
{
public string Name { get; set; }
public string Description { get; set; }
}
}
请注意,这个答案中没有提及任何云计算品牌商,因为这个问题是关于WPF中ListBoxItem绑定的问题。
领取专属 10元无门槛券
手把手带您无忧上云