在WPF中使用代码创建ListBox的ItemTemplate

3
我将尝试为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;

请帮我解决这个问题。我在网上找不到任何相关信息。

提前感谢您的帮助。

2个回答

4
尝试在绑定中使用点号.,这相当于{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;
    }
}

现在,如果我想将ItemsSource绑定到ObservableCollection,并将TextBlockFactory绑定到DisplayMemberPath,该怎么办?我的意思是,你能否提供一种方法,让我可以使用模板,无论是否将ItemsSource绑定到ObservableCollection都可以使用? - user3530012
@user3530012: 当然我可以,但是你应该创建一个新的问题。我不能在评论中回答你的新问题。 - Anatoliy Nikolaev
我在这里问过:http://stackoverflow.com/questions/23081311/create-itemtemplate-for-listbox-in-code-behind-in-wpf-part-ii - user3530012

0
尝试绑定“listbox”与ItemsSource,然后像下面的datatemplate一样指定,例如,如果要绑定名称,则只需编写{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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接