在列表框上加载数据模板
本文关键字:数据 加载 列表 | 更新日期: 2023-09-27 18:08:42
我已经创建了一个数据模板,并将其用作列表框上的资源,但是列表框没有显示我的数据模板。下面是数据模板定义的代码
<Window.Resources>
<DataTemplate x:Key="template1">
<Canvas Height="40" Width="850">
<TextBlock Height="40" Width="40" Canvas.Top="10" Foreground="Aqua">
</TextBlock>
<Label>hello</Label>
</Canvas>
</DataTemplate>
</Window.Resources>
列表框的代码在这里
<TabItem>
<Canvas Height="700" Width="850">
<ListBox Height="700" Width="850" ItemTemplate="{StaticResource template1}">
</ListBox>
</Canvas>
</TabItem>
我错在哪里??
1)如果您使用tabitem而不使用tabcontrol,则在将itemsource应用于Listbox后不显示输出
2)如果你想显示数据模板(显示你的数据),那么你必须为listbox绑定itemsource。
<<p> xaml代码/strong><Window.Resources>
<DataTemplate x:Key="template1">
<Canvas Height="40" Width="850">
<TextBlock Height="40" Width="40" Canvas.Top="10" Foreground="Aqua"></TextBlock>
<Label Content="{Binding State}"></Label>
</Canvas>
</DataTemplate>
</Window.Resources>
<TabControl>
<TabItem>
<Canvas Height="700" Width="850">
<ListBox Height="700" Width="850" ItemsSource="{Binding}" ItemTemplate="{StaticResource template1}">
</ListBox>
</Canvas>
</TabItem>
</TabControl>
c#代码
public partial class MainWindow : Window
{
private ObservableCollection<City> cities = new ObservableCollection<City>();
public MainWindow()
{
InitializeComponent();
cities.Add(new City() { Name = "Boston", State = "MA", Population = 3000000 });
cities.Add(new City() { Name = "Los Angeles", State = "CA", Population = 7000000 });
cities.Add(new City() { Name = "Frederick", State = "MD", Population = 65000 });
cities.Add(new City() { Name = "Houston", State = "TX", Population = 5000000 });
DataContext = cities;
}
class City
{
public string State { get; set; }
public string Name { get; set; }
public int Population { get; set; }
}
}
3)你也可以设计ListBoxItem ContentTemplate。
<Window.Resources>
<Style x:Key="ListboxItem" TargetType="ListBoxItem">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Canvas Height="40" Width="850">
<TextBlock Height="40" Width="40" Canvas.Top="10" Foreground="Aqua"></TextBlock>
<Label Content="{Binding Content,RelativeSource={RelativeSource TemplatedParent}}"/>
</Canvas>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<TabControl>
<TabItem Background="Red">
<ListBox Height="700" Width="850" ItemContainerStyle="{StaticResource ListboxItem}">
<ListBoxItem Content="Hello" Foreground="red"></ListBoxItem>
<ListBoxItem Content="Hello1"></ListBoxItem>
<ListBoxItem Content="Hello2"></ListBoxItem>
</ListBox>
</TabItem>
</TabControl>