![](/img/trans.png)
[英]How to bind Combobox dynamically Inside a datagrid in silverlight?
[英]Silverlight: How to dynamically bind a ComboBox in a ListBox ItemTemplate?
我有一个列表框,至少需要一个ComboBox。 我找不到将ComboBox放在我使用的ItemTemplate中的方法。
...
<DataTemplate x:Key="parts_template">
<StackPanel Orientation="Horizontal">
<TextBlock .../>
<ComboBox .../>
</StackPanel>
</DataTemplate>
...
<ListBox x:Name="lb_parts" ItemTemplate="{StaticResource parts_template}" .../>
...
如何将DataTemplate中的ComoBox绑定到后面代码中的ObservableCollection?
您可以尝试的另一件事是在ComboBox上预订Loaded事件。 然后,可以将EventHandler中的ComboBox.ItemsSource设置为MyObservableCollection。
看一看
XAML:
<DataTemplate x:Key="parts_template">
<StackPanel Orientation="Horizontal">
<TextBlock .../>
<ComboBox Loaded="ComboBox_OnLoaded">
<!-- ComboBox ItemTemplate -->
</ComboBox>
</StackPanel>
</DataTemplate>
后面的C#代码:
private void ComboBox_OnLoaded(object sender, EventArgs e)
{
((ComboBox)sender).ItemsSource = MyObservableCollection;
}
好的,这是在后面的代码中将ComboBox添加到ListBox的方法。
创建一个组合框
ComboBox x = new ComboBox();
如果您有填充ComboBox的数据源,则可以将其绑定
x.ItemsSource = e.Result;
如果您不愿意并且想要手动将项目添加到ComboBox:
ComboBoxItem y = new ComboBoxItem();
将项目的内容设置为想要在组合框中显示的内容
y.Content = "Hello";
现在剩下的就是将ComboBoxItem添加到ComboBox(仅当您手动创建Items时),然后将ComboBox添加到ListBox。
x.Items.Add(y);
//testing is my ListBox
testing.Items.Add(x);
您应该能够将数据上下文设置为列表本身
lb_Parts.DataContext=myCollection;
然后,您应该可以在模板中将其绑定
<DataTemplate x:Key="parts_template">
<StackPanel Orientation="Horizontal">
<TextBlock .../>
<ComboBox ItemSource={Binding}/>
</StackPanel>
</DataTemplate>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.