簡體   English   中英

以編程方式綁定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 });

但它不能正常工作,因為它只顯示以下內容: 鏈接到這里

它應該顯示CategoryNames:“拳頭”“第二”“第三”

我認為問題出在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屬性的綁定。 我已經更新了代碼片段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM