在WPF中的代码中为ListBox创建ItemTemplate

本文关键字:ListBox 创建 ItemTemplate 代码 WPF | 更新日期: 2023-09-27 17:58:34

我试图以编程方式为ListBox创建一个ItemTemplate,但它不起作用。我知道在XAML中我可以有类似的东西:

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

但是,当我试图以编程方式获得上述结果时,我面临一个问题,即绑定TextBox.TextProperty:

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

请在这个问题上帮助我。我在网上找不到关于它的任何信息。

提前谢谢。

在WPF中的代码中为ListBox创建ItemTemplate

尝试在绑定中使用点.,这相当于{Binding}

示例:

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

试试这个,通过将"listbox"与ItemsSource绑定并指定下面的数据模板,就像如果你想绑定名称,那么只需写入{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>