给定ComboBox
的ItemsControl
将有不同的项目,这些项目基于DataContext
项目的 (而不是ItemsControl
)。可以做到吗?如何?最好来自后面的代码。
我有以下内容DataModel
:
class Tester
{
public Tester(string name, string surname)
{
Name = name;
Surname = surname;
}
public string Name { get; set; }
public string Surname { get; set; }
public override string ToString()
{
return Name + " " + Surname;
}
}
class TheT
{
public ObservableCollection<Tester> TesterObject;
public TheT()
{
TesterObject = new ObservableCollection<Tester>();
}
public string myDisplayName { get { return "test"; } }
public void Add(Collection<Tester> col)
{
TesterObject.Clear();
foreach (Tester t in col) { TesterObject.Add(t); }
}
}
在Window
代码中我有:
ObservableCollection<TheT> myDataV ;
Public MainWindow()
{
InitializeComponent();
ObservableCollection<Tester> Tester1 = new ObservableCollection<Tester>();
Tester1.Add(new Tester("Sunny", "Jenkins"));
Tester1.Add(new Tester("Pieter", "Pan"));
ObservableCollection<Tester> Tester2 = new ObservableCollection<Tester>();
Tester2.Add(new Tester("Jack", "Sanders"));
Tester2.Add(new Tester("Bill", "Trump"));
myDataV = new ObservableCollection<TheT>();
myDataV.Add(new TheT(Tester1));
myDataV.Add(new TheT(Tester2));
IControl.ItemsSource = myDataV;
IControl.ItemTemplate = TestingDT;
}
IControl
ItemsControl
成立于XAML
:
<ItemsControl x:Name="IControl" Margin="53,375,81,63">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
而且DataTemplate
我已经尝试了各种方法。但仍然没有显示如下所示的项目:
// the DataTemplate
private DataTemplate TestingDT
{
get
{
DataTemplate DFT = new DataTemplate();
DFT.DataType = typeof(TheT);
FrameworkElementFactory Item = new FrameworkElementFactory(typeof(ComboBox));
Binding B = new Binding("TesterObject")
{
Source = this
};
Item.SetBinding(ComboBox.ItemsSourceProperty, B);
//Item.SetValue(ComboBox.DisplayMemberPathProperty, "Name");
DFT.VisualTree = Item;
return DFT;
}
}