【发布时间】:2018-11-28 15:37:13
【问题描述】:
我需要一个组合框的集合,其中包含可能的选择的公共集合。
代码隐藏摘录:
namespace ComboBoxesInCollection
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
D = new DataContainer();
this.DataContext = D;
}
private DataContainer D;
}
public class DataContainer
{
public ObservableCollection<Item> ComboboxItems
{
get { return comboboxItems; }
}
public ObservableCollection<Selection> ComboboxSelections
{
get { return comboboxSelections; }
}
public DataContainer()
{
comboboxItems = new ObservableCollection<Item>
{
new Item(100, "Entry #1"),
new Item(101, "Entry #2"),
new Item(102, "Entry #3")
};
comboboxSelections = new ObservableCollection<Selection>()
{
new Selection(1),
new Selection(2),
new Selection(3)
};
}
private ObservableCollection<Item> comboboxItems;
private ObservableCollection<Selection> comboboxSelections;
}
}
XAML 摘录:
<Window.Resources>
<DataTemplate x:Key="CSTemplate">
<Border BorderBrush="Black" BorderThickness="1,1,0,0" Margin="0,0,0,4" Padding="4">
<StackPanel>
<Label Content="{Binding Id}"/>
<ComboBox
ItemsSource="{Binding ComboboxItems}" //<= does not work
DisplayMemberPath="Name"
SelectedValue="{Binding SelectedId}"
SelectedValuePath="Id"
/>
</StackPanel>
</Border>
</DataTemplate>
...
<ItemsControl ItemsSource="{Binding ComboboxSelections}" ItemTemplate="{StaticResource CSTemplate}"/>
ItemsControl 显示项目,但 Combobox 为空。
我知道我尝试访问当前不存在的 Selection 内的属性/集合。
如何正确指定 DataBinding 以便我可以看到项目?
【问题讨论】:
-
ItemsControl 的 ItemTemplate 中元素的 DataContext 是其 ItemsSource 集合中的关联元素,即一个 Selection 对象。为了绑定到“父”视图模型,编写像
ItemsSource="{Binding DataContext.ComboboxItems, RelativeSource={RelativeSource AncestorType=ItemsControl}}"这样的绑定 -
我假设您希望看到一个组合框显示值 1,2 和 3 ?还是 3 个组合框,每个组合框连续显示 1,2 和 3?
-
如果这是静态数据,那么您可以将其设为资源。您可以将 observablecollection 放入具有默认设计器数据的资源中,并在运行时从数据库中填充它。 social.technet.microsoft.com/wiki/contents/articles/…
-
@auburg 三个组合框显示 1,2 和 3
-
@Clemens 您的建议有效,这正是我想要的,谢谢!您可能希望将其添加为实际答案
标签: wpf data-binding