简体   繁体   English

WPF组合框中所选项目的模板与组合集合中的项目的模板不同

[英]Different template for selected item in WPF combobox than items in composite collection

I have a composite collection which consists of: 我有一个包含以下内容的复合集合:

  • combobox item with content 'Select a vendor' 内容为“选择供应商”的组合框项目
  • collection container with collection of Vendor objects, bound to a combobox cmbVendor 具有绑定到组合框cmbVendor的Vendor对象的集合的容器

When a vendor is selected from the combobox, the ToString() method is called. 当从组合框中选择一个供应商时,将调用ToString()方法。 However, I want to display the value of the property Name of the selected Vendor object. 但是,我想显示所选Vendor对象的属性Name的值。 在此处输入图片说明 在此处输入图片说明

Setting the combobox property DisplayMemberPath='Name' works but then the 'Select a vendor' is not shown anymore on load, which is not desired. 设置组合框属性DisplayMemberPath='Name'可以,但是加载时不再显示“选择供应商”,这是不希望的。

Notes: 笔记:

  • sometimes a Vendor object is chosen from code-behind 有时从代码隐藏中选择一个Vendor对象
  • I can not override ToString() method of a Vendor object for other reasons 由于其他原因,我无法覆盖Vendor对象的ToString()方法

Any suggestions? 有什么建议么?

XAML 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>

VendorConverter VendorConverter

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;
        }
    }

Behaviors 行为

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;
            }
        }
    }

Approach 1 方法1

You should be able to combine TextSearch.TextPath="Name" for your normal items and TextSearch.Text="Select a vendor" directly assigned to your special item: 您应该能够将正常项目的TextSearch.TextPath="Name"和直接分配给特殊项目的TextSearch.Text="Select a vendor"组合在一起:

<ComboBox
    IsEditable="True"
    TextSearch.TextPath="Name">
...

and

<CompositeCollection>
    <ComboBoxItem Content='Select a vendor' TextSearch.Text="Select a vendor" />
    <CollectionContainer Collection='{Binding Source={StaticResource VendorsCollection}}' />
</CompositeCollection>

Approach 2 方法2

Just display a visual hint text when nothing is selected: 只要不选择任何内容,仅显示视觉提示文本:

<ComboBox
    ItemsSource="{Binding Source={StaticResource VendorsCollection}}"
    IsEditable="True">
    <ComboBox.Style>
        <Style TargetType="ComboBox">
            <Style.Resources>
                <VisualBrush x:Key="hintText" x:Shared="False"  AlignmentX="Left" Stretch="None">
                    <VisualBrush.Visual>
                        <Grid Background="White">
                            <TextBlock Margin="4 3" Text="Select a vendor"/>
                        </Grid>
                    </VisualBrush.Visual>
                </VisualBrush>
            </Style.Resources>
            <Style.Triggers>
                <Trigger Property="Text" Value="">
                    <Setter Property="Background" Value="{StaticResource hintText}"/>
                </Trigger>
                <Trigger Property="Text" Value="{x:Null}">
                    <Setter Property="Background" Value="{StaticResource hintText}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </ComboBox.Style>
</ComboBox>

This way, you can keep your items collection clean of extra entries and use TextSearch.TextPath and similar properties for your actual items. 这样,您可以使项目集合中没有多余的条目,并为您的实际项目使用TextSearch.TextPath和类似的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM