我有一个复合集合,其中包括:
- 内容为“选择供应商”的组合框项目
- 包含供应商对象集合的集合容器,绑定到组合框
cmbVendor
从组合框中选择供应商时,将ToString()
调用该方法。但是,我想显示Name
所选 Vendor 对象的属性值。
设置组合框属性DisplayMemberPath='Name'
有效,但加载时不再显示“选择供应商”,这是不希望的。
笔记:
- 有时从代码隐藏中选择 Vendor 对象
ToString()
由于其他原因,我无法覆盖供应商对象的方法
有什么建议么?
XAML
<UserControl.Resources>
<converters:VendorConverter x:Key='VendorConverter' />
<CollectionViewSource x:Key='VendorsCollection'
Source='{Binding Vendors}'>
</CollectionViewSource>
</UserControl.Resources>
<Grid>
<ComboBox Name='cmbVendor'
SelectedItem='{Binding Vendor, Converter={StaticResource VendorConverter}, Mode=TwoWay}'
IsSynchronizedWithCurrentItem='True'
IsEditable='True'
Width='{DynamicResource VendorCmbWidth}'>
<!--Make sure "Select a vendor" is selected-->
<i:Interaction.Behaviors>
<behaviour:SelectFirstItemBehavior />
</i:Interaction.Behaviors>
<ComboBox.Resources>
<DataTemplate DataType='{x:Type objects:Vendor}'>
<StackPanel Orientation='Horizontal'>
<TextBlock Text='{Binding Name}' />
</StackPanel>
</DataTemplate>
<DataTemplate DataType='{x:Type system:String}'>
<StackPanel Orientation='Horizontal'>
<TextBlock Text='{Binding }' />
</StackPanel>
</DataTemplate>
</ComboBox.Resources>
<ComboBox.ItemsSource>
<CompositeCollection>
<ComboBoxItem Content='Select a vendor' />
<CollectionContainer Collection='{Binding Source={StaticResource VendorsCollection}}' />
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>
</Grid>
</UserControl>
供应商转换器
internal class VendorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var vendor = value as Vendor;
if (vendor != null)
{
return vendor;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var comboboxItem = value as ComboBoxItem;
if (comboboxItem != null)
{
return null;
}
var vendor = value as Vendor;
if (vendor != null)
{
return vendor;
}
return null;
}
}
行为
internal class SelectFirstItemBehavior : Behavior<ComboBox>
{
protected override void OnAttached()
{
AssociatedObject.SelectionChanged += AssociatedObject_SelectionChanged;
}
protected override void OnDetaching()
{
AssociatedObject.SelectionChanged -= AssociatedObject_SelectionChanged;
base.OnDetaching();
}
private void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var combobox = sender as ComboBox;
if (combobox != null && combobox.SelectedIndex == -1)
{
combobox.SelectedIndex = 0;
}
}
}