我一直在XAML中绑定ListBox ItemsSource。如何从代码隐藏文件中的c#代码中进行绑定?
答案 0 :(得分: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