以编程方式绑定wpf列表框

时间:2015-11-10 15:15:20

标签: c# wpf xaml binding listbox

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:&#34; Fist&#34; &#34;第二&#34; &#34;第三&#34;

我认为问题在于我的文本绑定在列表框中,但我不知道如何解决它。

1 个答案:

答案 0 :(得分:0)

您还需要以编程方式创建数据模板。然后,您只需将数据模板分配给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属性的绑定。我已经更新了代码片段。