以编程方式绑定 wpf 列表框

Binding wpf listbox programmatically

这在 C# 代码中的等效项是什么?

<ListBox Name="CategoryListBox"
     ItemsSource="{Binding OtherList}"
     HorizontalAlignment="Left"
     Height="195"
     Margin="34,224,0,0"
     VerticalAlignment="Top"
     Width="120">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding CategoryName}" />
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox> 

我试过这样的东西:

        ListBox CategoryListBox = new ListBox();
        CategoryListBox.HorizontalAlignment = HorizontalAlignment.Left;
        CategoryListBox.VerticalAlignment = VerticalAlignment.Top;
        CategoryListBox.Height = 420;
        CategoryListBox.Width = 300;
        CategoryListBox.Margin = new Thickness(22, 93, 0, 0);
        BindingOperations.SetBinding(CategoryListBox, TextBox.DataContextProperty, new Binding("CategoryName") { Source = OtherList });
        BindingOperations.SetBinding(CategoryListBox, ListBox.ItemsSourceProperty, new Binding("OtherList") { Source = this });

但它没有正常工作,因为它只显示了这个: Link Here

它应该显示 CategoryNames: "Fist" "Second" "Third"

我认为问题出在我在 ListBox 中的文本绑定,但我不知道如何解决它。

您还需要以编程方式创建数据模板。然后你可以简单地将数据模板分配给ListBox的ItemTemplate 属性.

数据模板可以在 XAML 中创建并以编程方式加载。这可能会使创建模板更容易和更易于维护。

public partial class MainWindow : Window
{
    public class Category
    {
        public string CategoryName { get; set; }
    }

    public List<Category> categories = new List<Category>
    {
        new Category { CategoryName = "Category 1" },
        new Category { CategoryName = "Category 2" }
    };

    public MainWindow()
    {
        InitializeComponent();

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

        textBlock.SetBinding(TextBlock.TextProperty, new Binding("CategoryName"));

        var dataTemplate = new DataTemplate
        {
            VisualTree = textBlock
        };

        var categoryListBox = new ListBox
        {
            ItemTemplate = dataTemplate
        };

        BindingOperations.SetBinding(categoryListBox, ItemsControl.ItemsSourceProperty, new Binding
        {
            Source = categories
        });

        var grid = (Grid) this.Content;

        grid.Children.Add(categoryListBox);
    }
}

编辑:我的第一个例子不是为 ItemsSource 属性 创建绑定。为此,我更新了代码片段。