根据这个答案https://stackoverflow.com/a/33109026/426386 我将一个空的Item添加到我的ComboBox集合中。由于我的Combobox定义了SelectedValue和SelectedValuePath,我将遇到Bindingerrors:
<UserControl.Resources>
<ObjectDataProvider
x:Key="CardTypeProvider"
MethodName="GetLocalizedEnumValues"
ObjectType="{x:Type base:Localize}">
<ObjectDataProvider.MethodParameters>
<x:Type
TypeName="base:CardTypes" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</UserControl.Resources>
<ComboBox
DisplayMemberPath="Value"
SelectedValue="{Binding GroupByCardType, UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="Key">
<ComboBox.Resources>
<CollectionViewSource
x:Key="Items"
Source="{Binding Source={StaticResource CardTypeProvider}}" />
</ComboBox.Resources>
<ComboBox.ItemsSource>
<CompositeCollection>
<TextBlock />
<CollectionContainer
Collection="{Binding Source={StaticResource Items}}" />
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>
ObjectDataProvider返回以下类型:
Dictionary<Enum, string>
为了避免Binding错误,我想实例化一个KeyValuePair<Enum, string>
而不是TextBlock。可能以某种方式?
答案 0 :(得分:0)
我担心您无法在XAML中创建泛型类型的实例,并且您无法创建从值类型KeyValuePair&lt; TKey,TValue&gt;派生的类型。或者您可以创建另一个具有Key和Value属性的类型,并将此实例添加到CompositeCollection:
public class EmptyItem
{
public YourEnum Key { get; set; }
public string Value { get; set; } = "(Select)";
}
这应该满足绑定问题。
另一种选择是以编程方式添加实际的KeyValuePair&lt; TKey,TValue&gt;集合,例如:
CompositeCollection cc = comboBox.ItemsSource as CompositeCollection;
cc.Insert(0, new KeyValuePair<YourEnum, string>(..., "..."));