如何将多个组合框绑定到一个集合



我需要一个具有常见可能选择集合的组合框集合。

代码隐藏摘录:

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显示项目,但组合框为空。

我知道我试图访问当前不存在的Selection内部的属性/集合。

如何正确指定DataBinding以便查看项目?

使用元素绑定访问窗口的DataContext属性。

首先将窗口命名为x:Name="Window1",当绑定时,使用元素绑定。

ItemsSource="{Binding ElementName=Window1, Path=DataContext.ComboboxItems}" 

全窗口的XAML

<Window x:Class="WpfApp6.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp6"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" x:Name="Window1">
<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 ElementName=Window1, Path=DataContext.ComboboxItems}" 
DisplayMemberPath="Name" 
SelectedValue="{Binding SelectedId}" 
SelectedValuePath="Id" 
/>
</StackPanel>
</Border>
</DataTemplate>
</Window.Resources>
<Grid>
<ItemsControl ItemsSource="{Binding ComboboxSelections}" ItemTemplate="{StaticResource CSTemplate}" />
</Grid>

相关内容

最新更新