如何以编程方式将 ListBox ItemsSource 绑定到 ViewModel 属性(这是一个集合)?

How to bind ListBox ItemsSource to a ViewModel property (which is a Collection) programmatically?

我一直在XAML中绑定ListBox ItemsSource。如何从代码隐藏文件中以 C# 代码进行绑定?

步骤如下

  1. 在 XAML 中命名列表框控件,以便 C# 编译器可以通过该名称访问它。
  2. 通过 initializer/constructor 页面中的项目源加载列表框。

     myListBox.ItemsSource = myListName;
    

这就是我从代码设置绑定的方式,如果它有任何帮助的话:

            //chk = CheckBox object
            //item = the object in my model on the Window/User control datacontext
            //IsChecked = name of the property inside item that I bind to the checkbox

            Binding myBinding = new Binding("IsChecked");
            myBinding.Source = item;

            //If your property should be not a boolean you can set a converter
            //In this sample I have a String to boolean converter if needed
            //myBinding.Converter = new StringToBoolConverter();

            //Set the binding mode, oneway, twoway or whatever
            myBinding.Mode = BindingMode.TwoWay;
            //Indicate to the binding that the Property Change is triggering and update
            myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;

            //Set the binding in the Checkbox object on my window
            chk.SetBinding(CheckBox.IsCheckedProperty, myBinding);

但是,如果您只需要设置列表框的 ItemSource,则无需构建绑定,只需在 XAML

中为列表框指定一个名称即可
<Listbox Name=MyListbox....>

然后在后面的代码中将 ItemSource 属性 设置为您的模型 属性:

MyListbox.ItemSource = mymodel.MyListProperty