Create ItemTemplate for ListBox in code-beind in WPF

人盡茶涼 提交于 2019-12-13 14:51:16

问题


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.


回答1:


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;
    }
}



回答2:


Try this, by binding the "listbox" with ItemsSource and specify the datatemplate below like if you want to bind name then just write {Binding Name}

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


来源:https://stackoverflow.com/questions/23079496/create-itemtemplate-for-listbox-in-code-beind-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!