WPF ComboBox自动选择如果只有1项 [英] WPF ComboBox Auto Select If Only 1 Item

查看:145
本文介绍了WPF ComboBox自动选择如果只有1项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组合框,我绑定到一个可观察的集合,它被更改(根据公司选择)和大量的公司将有一个单一的帐户(项目),因此我想知道什么最好的方法如果ItemsSource中只有一个项目,则使ComboBox设置SelectedItem,否则保留为null以确保用户选择一个帐户。

I have a combo box that I bind to an observable collection, which gets changed (according to company selected) and a large number of companies will have a single account (the items) therefore I want to know what the best way to make the ComboBox set the SelectedItem if there is only 1 item in the ItemsSource, otherwise leave it as null to ensure the user chooses an account.

目前是通过在每次更改时检查帐户集合,并且如果只包含一个,则将绑定的选定项目属性设置为集合中的第一个项目。

The way I am doing this at the moment is by checking the account collection each time it is changed, and if it contains only one, setting the bound selected item property to the first item in the collection.

这看起来很长,我需要单独实现它到每个视图模型,并为每个组合框写最多5行代码。

This seems long winded and I would need to implement it into each view model separately and write up to 5 lines of code for each combo box.

以下是代码我目前,但我想知道是否有可能实现这一点通过扩展ComboBox控件?如果有人对如何/在哪里开始有任何想法。

The following is the code I currently, but I was wondering if there would it be possible to achieve this by extending the ComboBox control? And if anyone has any ideas on how/where to start.

    public CompanyGermanPower FromCompany
    {
        get { return _fromCompany; }
        set
        {
            SetField(ref _fromCompany, value, () => FromCompany);
            if(value!= null)
            {
                FromTradeAccountList = new ObservableCollection<TradeAccount>(TradeAccountAdapter.GetTradeAccounts(_session, value.ID));
                if (Trade != null && FromTradeAccountList.Count == 1) Trade.TradeAccountFrom = FromTradeAccountList[0];
            }
        }
    } private CompanyGermanPower _fromCompany;


推荐答案

创建附加行为,做你想要的。要检测ComboBox中的Items集合何时更改,您需要使用此 blog post

It should be fairly straightforward to create an Attached Behaviour that does what you want. To detect when the Items collection in the ComboBox changed, you'd need to use the trick mentioned in this blog post.

更新:这是我的刺需要为您的项目添加对System.Windows.Interactivity的引用 - 您可以从Expression Blend SDK中获取它):

Update: Here's my stab at it (you'll need to add a reference to System.Windows.Interactivity to your project - you can get it from the Expression Blend SDK):

using System.Windows.Interactivity;

public class SelectFirstItemComboBoxBehavior : Behavior<ComboBox>
{
    protected override void OnAttached()
    {
        base.OnAttached();

        (AssociatedObject.Items as INotifyCollectionChanged).CollectionChanged += HandleCollectionChanged;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        (AssociatedObject.Items as INotifyCollectionChanged).CollectionChanged -= HandleCollectionChanged;
    }

    private void HandleCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (AssociatedObject.Items.Count == 1)
        {
            AssociatedObject.SelectedItem = AssociatedObject.Items.Cast<object>().First();
        }
    }
}

<Window x:Class="ComboBoxSelectFirstBehavior.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ComboBoxSelectFirstBehavior"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.Resources>
        <x:Array x:Key="MyObjects" Type="{x:Type local:MyType}">
            <local:MyType Name="WithChildren">
                <local:MyType.Children>
                    <local:MyTypeCollection>
                        <local:MyType Name="Child1"/>
                        <local:MyType Name="Child2"/>
                        <local:MyType Name="Child3"/>
                    </local:MyTypeCollection>
                </local:MyType.Children>
            </local:MyType>
            <local:MyType Name="WithOneChild">
                <local:MyType.Children>
                    <local:MyTypeCollection>
                        <local:MyType Name="Child1"/>
                    </local:MyTypeCollection>
                </local:MyType.Children>
            </local:MyType>
            <local:MyType Name="WithoutChildren">
                    <local:MyType.Children>
                        <local:MyTypeCollection>
                        </local:MyTypeCollection>
                    </local:MyType.Children>
                </local:MyType>
        </x:Array>
    </Grid.Resources>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <ComboBox x:Name="FirstCombo" Grid.Row="0" ItemsSource="{StaticResource MyObjects}" DisplayMemberPath="Name"/>

    <ComboBox Grid.Row="1" ItemsSource="{Binding ElementName=FirstCombo, Path=SelectedItem.Children}" DisplayMemberPath="Name">
        <i:Interaction.Behaviors>
            <local:SelectFirstItemComboBoxBehavior/>
        </i:Interaction.Behaviors>
    </ComboBox>
</Grid>

这篇关于WPF ComboBox自动选择如果只有1项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆