我有四个组合框经历了一个奇怪的怪癖。它的我很难解释究竟怎么回事...所以我把它放在一个视频:ComboBoxes共享Observable集合不断打破
https://www.youtube.com/watch?v=OuB-kSGMMSo
<ComboBox x:Name="images1" Grid.Row="0" Grid.Column="0" Margin="3"/>
<ComboBox x:Name="images2" Grid.Row="0" Grid.Column="1" Margin="3"/>
<ComboBox x:Name="images3" Grid.Row="0" Grid.Column="2" Margin="3"/>
<ComboBox x:Name="images4" Grid.Row="0" Grid.Column="3" Margin="3"/>
代码背后
public ObservableCollection<ComboBoxItem> images =
new ObservableCollection<ComboBoxItem>();
public ImageSelect(MainWindow mainWindow, string tab_name)
{
InitializeComponent();
Generic.ImportImages(tab_name, images1, images);
images2.ItemsSource = images;
images3.ItemsSource = images;
images4.ItemsSource = images;
}
我班
public static void ImportImages(string tabID, ComboBox combo, ObservableCollection<ComboBoxItem> list)
{
try
{
string root = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
var files = Directory.GetFiles(Path.Combine(root, "input\\" + tabID), "*.png");
foreach (var file in files)
{
string[] paths = file.Split('\\');
ComboBoxItem item = new ComboBoxItem();
item.Tag = paths.Last();
var stack = new StackPanel() { Orientation = Orientation.Horizontal };
stack.Children.Add(new Image() { Source = new BitmapImage(new Uri(file, UriKind.Absolute)), Height = 44 });
stack.Children.Add(new Label() { Content = paths.Last(), VerticalContentAlignment = VerticalAlignment.Center });
item.Content = stack;
list.Add(item);
}
}
catch (Exception) { }
combo.ItemsSource = list;
}
UI元素可以在一个以上的地方在视觉树不存在(或多于一个的可视化树) ;您不能将相同的'ComboBoxItem'添加到多个'ComboBox'。 – 2014-10-09 20:51:22
那么,我将如何完成我想要做的? – 2014-10-09 20:52:25
理想情况下,您应该使用对象模型来表示组合框(它不是UI元素,因此可以共享)中显示的项目,并设置一个“ItemTemplate”来告诉每个“ComboBox”如何呈现支持对象(例如用标签和图像)。在我离开办公室之前,我没有时间写出正确的答案,但我想我至少可以让你朝正确的方向发展,或者让其他人在答案中取得领先。 – 2014-10-09 20:54:32