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

时间:2015-08-24 13:32:20

标签: c# windows-phone-8 data-binding

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

2 个答案:

答案 0 :(得分:2)

以下是步骤

  1. 在XAML中命名列表框控件,以便C#编译器可以通过该名称访问它。
  2. 在页面初始值设定项/构造函数中按项目源加载列表框。

     myListBox.ItemsSource = myListName;
    

答案 1 :(得分:1)

这是我如何设置代码中的Bindings,如果它可以提供任何帮助:

            //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);

但是,如果您只需要设置Listbox的ItemSource,则不需要构建绑定,但只需在XAML中为Listbox指定一个名称

<Listbox Name=MyListbox....>

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

MyListbox.ItemSource = mymodel.MyListProperty