在WPF中的code-beind中为ListBox创建ItemTemplate

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

       

但是当我试图以编程方式获得上述结果时,我遇到了一个绑定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

    

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绑定并指定下面的datatemplate就像你想要绑定名称然后只写{Binding Name}