在WPF中的代码隐藏中为ListBox创建ItemTemplate [英] Create ItemTemplate for ListBox in code-beind in WPF

查看:121
本文介绍了在WPF中的代码隐藏中为ListBox创建ItemTemplate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以编程方式为ListBox创建ItemTemplate,但是它不起作用.我知道在XAML中我可以拥有类似的东西:

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>

但是当我试图以编程方式获得上述结果时,我遇到了绑定TextBox.TextProperty的问题:

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.

提前谢谢.

推荐答案

尝试在Binding中使用点.,这等效于{Binding}.

Try use dot . in Binding, this is the equivalent of {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;
    }
}

这篇关于在WPF中的代码隐藏中为ListBox创建ItemTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆