複数の選択は簡単にWinUI


統合WinUI ComboBox ( SfComboBox )ユーザーが値を入力するか、定義済みのドロップダウンリストからオプションを選択できるようにする選択コントロールです.これは、単一と複数の選択をサポートします.複数の選択は、チェックボックスでも表示できます.
このブログ記事では、コード例でWinUI ComboBoxコントロールで複数選択機能を使用する方法を確認します.
注意:前に進む前にGetting Started with WinUI ComboBox documentation および.

データを準備する
人々のために電子メール情報を格納するためにモデルを作成して、WinUI ComboBoxコントロールでそれを受け入れましょう.
次のコードを参照してください.
Public class Person
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string EmailID { get; set; }
}
次に、WinUIコンボボックスコントロールのデータソースを格納するViewModelクラスを作成します.
public class ViewModel : NotificationObject
{
    public ViewModel()
    {
        Persons = new ObservableCollection<Person>();
        Persons.Add(createNewPerson(Anne, Dodsworth, anne.dodsworth@mail.com));
        ...
    }

    public ObservableCollection<Person> Persons { get; set; }

    private Person CreateNewPerson(string firstName, string lastName, string eMail)
    {
        return new Person
        {
            FirstName = firstName,
            LastName = lastName,
            EmailID = eMail
        };
    }
}

複数選択の有効化
シングルセレクションは、WinUIコンボボックスコントロールの既定の選択モードです.SelectionModeプロパティを複数に設定することで変更できます.
複数選択機能には2つの表示モードがあります.デリミタモードでは、編集をサポートしません.編集によって人々を選択しなければならないので、MultiSelectionDisplayModeプロパティをトークンモードに設定します.
次に、ドロップダウンリスト内のメールIDを表示するテンプレートを定義し、エディタで選択したユーザー名(firstNameとLastNameの両方)を表示します.
次のコード例を参照してください.
<Grid>
    <Grid.DataContext>
        <local:ViewModel/>
    </Grid.DataContext>
    <editors:SfComboBox ItemsSource=”{Binding Persons}”
                        SelectionMode=”Multiple”
                        MultiSelectionDisplayMode=”Token”
                        PlaceholderText=”Try anne>
        <editors:SfComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text=”{Binding EmailID}”/>
            </DataTemplate>
        </editors:SfComboBox.ItemTemplate>
        <editors:SfComboBox.TokenItemTemplate>
            <DataTemplate>
                <TextBlock>
                    <TextBlock.Inlines>
                        <Run Text=”{Binding FirstName}” />
                        <Run Text=”{Binding LastName}” />
                    </TextBlock.Inlines>
                </TextBlock>
            </DataTemplate>
        </editors:SfComboBox.TokenItemTemplate>
    </editors:SfComboBox>
</Grid>

WinUIコンボボックスコントロールで複数選択モード

編集とフィルタリングを有効にする
次に、次のコード例に示すように、編集、検索、およびフィルター処理の動作を有効にします.
<Grid>
    <editors:SfComboBox ItemsSource=”{Binding Persons}”
                        IsEditable=”True”
                        IsFilteringEnabled=”True”
                        IsTextSearchEnabled=”True”>
    </editors:SfComboBox>
</Grid>

カスタムフィルタリング
既定では、DisplayMemberPathまたはTextMemberPathプロパティに基づいてフィルター処理が実行されます.TextMemberPathプロパティは優先度が高い.
カスタムの基準に基づいて項目をフィルター処理するには、IComboBoxFilterBehaviorインターフェイスでカスタムフィルタリング動作を定義する必要があります.
ViewModelクラスで実装しましょう.GetMatchingIndexイベントは、ユーザーがエディタで入力を入力するたびに呼び出されます.このメソッドは、入力を含むドロップダウンリスト内のすべての項目のインデックスを返します.
次のコード例を参照してください.
Public class ViewModel : NotificationObject, IcomboBoxFilterBehavior
{
    public List<int> GetMatchingIndexes(SfComboBox source, ComboBoxFilterInfo filterInfo)
    {
        var items = Persons;
        var ignoreCase = StringComparison.InvariantCultureIgnoreCase;

        // Get person details whose name or email id contains the given input.
        Var filteredItems = items.Where(
                                person => person.FirstName.Contains(filterInfo.Text, ignoreCase) ||
                                person.LastName.Contains(filterInfo.Text, ignoreCase) ||
                                person.EmailID.Contains(filterInfo.Text, ignoreCase));

        // Find the indices of the items to be shown in the drop-down.
        Var indices = filteredItems.Select<Person, int>(p => items.IndexOf(p)).ToList();

        return indices;
    }
}
次に、ViewModelクラスでフィルター処理の動作を構成します.
<Grid>
    <editors:SfComboBox ItemsSource=”{Binding Persons}”
                        FilterBehavior=”{Binding}”>
    </editors:SfComboBox>
</Grid>
今、簡単にアイテムをフィルタリングできます.しかし、それはItemsSourceで加えられる順序で入力を含むアイテムを表示します.
例えば、私がNをタイプするならば、私はナンシーを最初に示すのを好みます.

アイテムのフィルタリング
簡単に我々の必要なアイテムをフィルタリングするには、優先順位に基づいてアイテムを並べ替える必要があります.入力テキストをstartwithする項目に優先順位を付けましょう.そして、次の優先度は、包含条件を満たす項目に進む.また、すでに選択した項目を表示することは避けられます.
次のコード例を参照してください.
Public class ViewModel : NotificationObject, IcomboBoxFilterBehavior
{
    public List<int> GetMatchingIndexes(SfComboBox source, ComboBoxFilterInfo filterInfo)
    {
        var items = Persons;
        var ignoreCase = StringComparison.InvariantCultureIgnoreCase;

        // Avoid showing already selected items in the drop-down.
        Var unselectedItems = Persons.Except(source.SelectedItems).OfType<Person>();

        // Get person details whose name or email id starts with the given input.
        Var firstPriority = unselectedItems.Where(
                                person => person.FirstName.StartsWith(filterInfo.Text, ignoreCase) ||
                                person.LastName.StartsWith(filterInfo.Text, ignoreCase) ||
                                person.EmailID.StartsWith(filterInfo.Text, ignoreCase));

        // Append person whose name or email id contains the given input.
        Var secondPriority = unselectedItems.Except(firstPriority).Where(
                                person => person.FirstName.Contains(filterInfo.Text, ignoreCase) ||
                                person.LastName.Contains(filterInfo.Text, ignoreCase) ||
                                person.EmailID.Contains(filterInfo.Text, ignoreCase));

        // Find the indices of the item to be shown in the drop-down.
        Var indices = firstPriority.Union(secondPriority).Select<Person, int>(p => items.IndexOf(p)).ToList();

        return indices;
    }
}

カスタムアイテムの動的選択
WinUI ComboBoxは、InputSubmitイベントを使用してItemsSourceにないカスタムアイテムを選択できます.このイベントは、指定された入力がITemsSource内の項目と一致しない場合に発行されます.
次に、InputPrimaryイベント引数のItemプロパティで必須項目(ドロップダウンリストではない)を設定し、選択リストに簡単に追加します.これは、ComboBoxコントロールのエディタにそれらを追加することによって、私たちの組織の外の人々にメールを送るのを助けます.
注:選択項目のカスタム項目を追加するには、WinUIコンボボックスのItemsSourceには含まれません.
次のコード例を参照してください.
Private async void OnInputSubmitted(object sender, ComboBoxInputSubmittedEventArgs e)
{
    var emailString = e.Text;
    bool isEmail = Regex.IsMatch(emailString, @”\A(?:[a-z0-9!#$%&*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z, RegexOptions.IgnoreCase);

    // If given input is in valid email format.
    if (isEmail)
    {
        // Create a new person for selection.
        Person newPerson = new Person();
        newPerson.EmailID = emailString;
        int atIndex = emailString.LastIndexOf(‘@’);
        int dotIndex = emailString.IndexOf(.);
        string name = emailString.Substring(0, atIndex);
        if (name.Contains(.))
        {
            newPerson.FirstName = name.Substring(0, dotIndex);
            newPerson.LastName = name.Substring(dotIndex + 1);
        }
        else
        {
            newPerson.FirstName = name;
        }
        e.Item = newPerson;
    }

    // If the email id is invalid, show error dialog.
    Else
    {
        var dialog = new ContentDialog();
        dialog.CloseButtonText = Close;
        dialog.Content = Invalid email id!;
        dialog.Title = Error;
        dialog.XamlRoot = this.Content.XamlRoot;
        await dialog.ShowAsync();
    }
}

WinUIコンボボックスの選択リストにカスタム項目を追加する

Githubリファレンス
詳細については、multiple selection made easy using the WinUI ComboBox control Githubについて

結論
読書ありがとう.私はあなたがmultiple selection 我々の特集WinUI ComboBox コントロール.WinUI ComboBoxまた、スタイル、テーマ、プレースホルダーのテキストをサポートしています.それらを試してみると以下のコメントセクションであなたのフィードバックを残す!
あなたがダウンロードすることができますし、当社のデモアプリをチェックアウトMicrosoft Store .
現在の顧客については、新しいバージョンからダウンロード可能ですLicense and Downloads ページ.まだSyncFusionの顧客でない場合は、私たちの30日を試すことができますfree trial 当社の最新機能をチェックアウトします.
また、私たちを介してお問い合わせすることができますsupport forums , support portal , or feedback portal . 我々は常にあなたを支援して満足している!

関連ブログ
  • Easily Schedule Recurring Events in WinUI Scheduler
  • Introducing the New WinUI 3 AutoComplete Control
  • 10 Features of WinUI Circular Charts That Make It Appealing
  • Everything You Need to Know About The WinUI Badge Control