如何以编程方式将ListBox ItemsSource绑定到ViewModel属性(这是一个集合)
本文关键字:属性 集合 一个 ViewModel 编程 方式 绑定 ItemsSource ListBox | 更新日期: 2023-09-27 18:09:26
我一直在XAML中绑定ListBox ItemsSource。我如何从代码后面的文件在c#代码中做绑定?
步骤如下
- 用XAML命名列表框控件,以便c#编译器可以通过该名称访问它。
-
按列表框的itemssource加载,例如在页面初始化器/构造器中。
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
中给列表框一个Name。<Listbox Name=MyListbox....>
然后在代码后面设置ItemSource属性为你的模型属性:
MyListbox.ItemSource = mymodel.MyListProperty