我使用的是ComboBox和CompositeCollection,如下所示:
<ComboBox>
<ComboBox.ItemsSource>
<CompositeCollection>
<ComboBoxItem Content="All"></ComboBoxItem>
<CollectionContainer Collection="{Binding Source={StaticResource AllBitsSource}}" />
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>所显示的数据与预期完全相同,只有我现在希望将默认的索引/值/项设置为ComboBoxItem的索引/值/项,并且存在一些问题。
如果我设置:
<ComboBoxItem Content="All" IsSelected="True"/>这就完全被忽视了。
我还试着做:
<ComboBox SelectedIndex="0">虽然这确实选择了All值,但当我打开下拉列表时,突出显示的值是加载到ComboBox上的最后一个值,而不是All值。
如何解决这个问题,以便使我的ComboBoxItem内容在绑定后保持选中?
编辑:
我刚刚尝试用另一个<ComboBoxItem>替换我的<ComboBoxItem>,虽然它们仍然在<CompositeCollection>中,但它的工作方式很好。
EDIT2:
显示问题所在的图像:

EDIT3:
AllBitsSource的代码:
XAML:
<Window.Resources>
<CollectionViewSource x:Key="AllBitsSource" Source="{Binding Path=AllBits}" />代码背后:
private readonly ObservableCollection<string> _bits = new ObservableCollection<string>();
private void GetCurrentSettings()
{
setttings = display.GetDisplaySettings();
foreach (var mode in setttings)
{
var displaySettingInfoArray = mode.GetInfoArray();
if (_bits.Contains(displaySettingInfoArray[4]) == false)
{
_bits.Add(displaySettingInfoArray[4]);
}
}
}
public ObservableCollection<string> AllBits
{
get { return _bits; }
}GetCurrentSettings()在Main()上被调用
发布于 2013-08-21 18:59:40
由于在构建ComboBox之后要添加到集合中,所以您可能必须访问加载的事件并在那里设置您的SelectedIndex .
<ComboBox Loaded="ComboBox_Loaded">
<ComboBox.ItemsSource>
<CompositeCollection>
<ComboBoxItem Content="All" />
<CollectionContainer Collection="{Binding Source={StaticResource AllBitsSource}}" />
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>代码背后:
private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
(sender as ComboBox).SelectedIndex = 0;
}https://stackoverflow.com/questions/18364557
复制相似问题