c# - 在 WPF 的代码隐藏中为 ListBox 创建 ItemTemplate

标签 c# wpf listbox styles itemtemplate

我正在尝试以编程方式为 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>

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

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

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

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

提前致谢。

最佳答案

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

例子:

XAML

<Window x:Class="MyNamespace.MainWindow"
        ...
        Loaded="Window_Loaded">

    <ListBox Name="MyListBox" ... />
</Window>

代码隐藏

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

关于c# - 在 WPF 的代码隐藏中为 ListBox 创建 ItemTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23079496/

相关文章:

c# - Dropbox 及其类似 "Folder"的设计

wpf 列表框将单个项目更改为粗体

c# - 来自另一个类的列表框计数项目始终返回 0

c# - 如何更改列表框的突出显示颜色

c# - 这个设计使用动态好吗?

c# - 痣和内部类

c# - WPF 嵌套 ListViews 滚动行为

wpf - Infragistics XamDatagrid 绑定(bind)问题

silverlight - 如何使用 Silverlight2 ItemsControl 在 Canvas 上定位项目集合?

c# - 使用 C# 快速获取 Active Directory 中组成员列表的方法