Search code examples
c#wpflistboxstylesitemtemplate

Create ItemTemplate for ListBox in code-beind in WPF


I'm trying to create an ItemTemplate for a ListBox programmatically but it doesn't work. I know in XAML I can have something like:

<ListBox x:Name="listbox" BorderThickness="0" Margin="6" Height="400">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Margin="0" Background="Red" Foreground="White" FontSize="18" Text="{Binding}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

But when I'm trying to have the above result programmatically I face a problem which is binding the TextBox.TextProperty:

var textblock = new FrameworkElementFactory(typeof(TextBlock));

// Setting some properties
textblock.SetValue(TextBlock.TextProperty, ??);
var template = new ControlTemplate(typeof(ListBoxItem));
template.VisualTree = textblock;

Please help me on this issue. I couldn't find anything on the web about it.

Thanks in advance.


Solution

  • Try use dot . in Binding, this is the equivalent of {Binding}.

    Example:

    XAML

    <Window x:Class="MyNamespace.MainWindow"
            ...
            Loaded="Window_Loaded">
    
        <ListBox Name="MyListBox" ... />
    </Window>
    

    Code-behind

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));
            textBlockFactory.SetValue(TextBlock.TextProperty, new Binding(".")); // Here
            textBlockFactory.SetValue(TextBlock.BackgroundProperty, Brushes.Red);
            textBlockFactory.SetValue(TextBlock.ForegroundProperty, Brushes.Wheat);
            textBlockFactory.SetValue(TextBlock.FontSizeProperty, 18.0);
    
            var template = new DataTemplate();            
            template.VisualTree = textBlockFactory;
    
            MyListBox.ItemTemplate = template;
        }
    }