Answer the question
In order to leave comments, you need to log in
How to programmatically create a DataTemplate in C# WPF (not using XAML)?
Actually the question has already been raised. You need to create something like this in code
<ListBoxItem>
<DataTemplate>
<Label></Label>
<Label></Label>
</DataTemplate>
</ListBoxItem>
Answer the question
In order to leave comments, you need to log in
Creating a DataTemplate from code is a very bad idea. Firstly, it is relatively difficult, secondly, any flexibility of declarative markup is lost, and thirdly, part of the functionality of templates is lost. Yes, and the bindings in the code to create such a thing are just overkill ...
Here is a normal approach: You bind the ItemsSource of the listbox to the ObservableCollection; create a DataTemplate in resources
<Window x:Class="listbox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:someData="clr-namespace:listbox"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate x:Key="CarItemTemplate" DataType="{x:Type someData:SomeData}">
<Border Background="DeepSkyBlue" Width="200" Margin="3" CornerRadius="4">
<Grid>
<TextBlock Text="{Binding Name}" Foreground="White" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="30"/>
<TextBlock Text="{Binding Count}" Foreground="White" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="3"/>
</Grid>
</Border>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox x:Name="lisbox" DataContext="{Binding}" ItemsSource="{Binding CarCollection}" ItemTemplate="{StaticResource CarItemTemplate}"></ListBox>
</Grid>
</Window>
namespace listbox
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public ObservableCollection<SomeData> CarCollection { get; set; }
public MainWindow()
{
InitializeComponent();
CarCollection = new ObservableCollection<SomeData>{
new SomeData{Name="BMW", Count=20},
new SomeData{Name="Mercedess", Count=30},
new SomeData{Name="Таврия", Count=200}
};
DataContext = this;
}
}
public class SomeData
{
public string Name { get; set; }
public int Count { get; set; }
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question