Usercontrol中具有CompositeCollection的WPF ComboBox不起作用:SelectedIndex设置为-1

时间:2017-11-28 09:01:22

标签: c# wpf xaml combobox user-controls

我正在使用MVVM。

我有一个由

组成的CompositeCollection
  • ComboboxItem with'选择供应商'作为内容
  • 有限的CollectionContainer

当我在视图中直接使用ComboBox XAML代码时,SelectedIndex设置为0(如预期的那样)。

enter image description here

但是,当我将ComboBox XAML代码放在Usercontrol中并在我的视图中使用该控件时,SelectedIndex设置为-1。 知道如何解决这个问题,以便我可以使用usercontrol吗?

enter image description here

我的所有绑定都有效。

注意:

  • 当Combobox XAML代码直接在视图中时:当'选择供应商'时,ComboboxConverter将Vendor属性设置为null。由用户选择。

但是,当ComboBox XAML代码在Usercontrol中时,代码不会进入

if (comboboxItem.Content.ToString() == "Select a vendor")
                {
                    //gets here when code is in view <-> code in control
                    return null;
                }

ComboboxConverter

public class ComboboxConverter : 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)
        {
            if (comboboxItem.Content.ToString() == "Select a vendor")
            {
                //gets here when code is in view <-> code in control
                return null;
            }
            return null;
        }

        var vendor = value as Vendor;
        if (vendor != null)
        {
            return vendor;
        }
        return null;
    }
}

VendorControl

<UserControl x:Class="Tool.Controls.VendorControl"
         xmlns:local="clr-namespace:Tool.Controls"
         xmlns:System="clr-namespace:System;assembly=mscorlib"
         xmlns:objects='clr-namespace:Tool.Objects'
         xmlns:converters='clr-namespace:Tool.Converters'
         mc:Ignorable="d" >
<UserControl.Resources>
<converters:ComboboxConverter x:Key='ComboboxConverter' />
</UserControl.Resources>
<Grid>
<ComboBox Name='cmbVendor'
              SelectedItem='{Binding Vendor, Converter={StaticResource ComboboxConverter}, Mode=TwoWay}'
              Grid.Column='1'
              IsSynchronizedWithCurrentItem='True'>
      <ComboBox.Resources>
    <CollectionViewSource x:Key='VendorsCollection'
                          Source='{Binding Vendors}' />            
        <DataTemplate DataType='{x:Type objects:Vendor}'>
          <StackPanel Orientation='Horizontal'>
            <TextBlock Text='{Binding Name}' />
          </StackPanel>
        </DataTemplate>
      </ComboBox.Resources>
      <ComboBox.ItemsSource>
        <CompositeCollection>
          <ComboBoxItem Content='Select a vendor' />
          <CollectionContainer Collection='{Binding Source={StaticResource VendorsCollection}}' />
        </CompositeCollection>
      </ComboBox.ItemsSource>
    </ComboBox>

视图模型

private void OnWindowLoaded()
    {
         LoadVendors();
    }

    ObservableCollection<Vendor> _vendors = new ObservableCollection<Vendor>();
    public ObservableCollection<Vendor> Vendors
    {
        get
        {
            return _vendors;
        }

    }


    private Vendor _vendor;
    public Vendor Vendor
    {
        get
        {
            return _vendor;
        }

        set
        {
            if (value != _vendor)
            {
                _vendor = value;
                RaisePropertyChanged(nameof(Vendor));
            }
        }
    }

private void LoadVendors()
    {
            var dVendors = VendorHelper.GetVendors();

            if (Vendors.Count > 0)
            {
                DispatcherHelper.CheckBeginInvokeOnUI(() => Vendors.Clear());
            }

            dVendors.ForEach(dV =>
            {
                var vendor = new Vendor(dV);
                DispatcherHelper.CheckBeginInvokeOnUI(() => Vendors.Add(vendor));
            });
    }

1 个答案:

答案 0 :(得分:2)

在您的Vendor为null时,函数Convert也将返回null,但是您的组合框不知道null意味着什么,这就是为什么它将其选定的索引值设置为-1的原因。 您可以通过创建一个在设置为-1时始终选择索引0的行为来解决此问题。

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

然后在你的XAML部分:

   xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

...

在你的Combobox里面

<i:Interaction.Behaviors>
    <SelectFirstItemBehavior/>
</i:Interaction.Behaviors>