4

動物のコレクションにバインドされた ComboBox があります。その中から好きな動物を選んでいます。バインドされたアイテムの上に静的な null アイテムが必要です。CompositeCollection を使用して宣言します。ComboBox がバインドされている場合、最初のお気に入りの動物は選択されません。どうすれば修正できますか?ここでも同様の問題がありますが、まだ解決されていません。

所見:

  • 静的アイテムへのバインドは機能します。つまり、最初のお気に入りの動物がない場合、静的アイテムが選択されます。
  • 静的アイテムを削除すると、問題はなくなります。もちろん、これにより CompositeCollection とこの質問全体が時代遅れになります。

私はすでにこれらの対策を適用しました:

  • CollectionContainer は、ここで概説されているようにプロパティに直接バインドできません。
  • ここで提案されているように、複合コレクションも静的リソースに移動されます。

問題を示すために C# コードと XAML を完成させます。

using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace WpfApplication1
{
    public class Animal
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class Zoo
    {
        private IEnumerable<Animal> _animals = new Animal[]
        {
            new Animal() { Id = 1, Name = "Tom" },
            new Animal() { Id = 2, Name = "Jerry" }
        };

        public Zoo(int initialId)
        {
            FavouriteId = initialId;
        }

        public int FavouriteId { get; set; }
        public IEnumerable<Animal> Animals { get { return _animals; } }
    }

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void BindComboBox(object sender, RoutedEventArgs e)
        {
            // Selecting the static item by default works.
            //DataContext = new Zoo(-1);

            // Selecting "Jerry" by default does not work.
            DataContext = new Zoo(2);
        }
    }
}

XAML

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1">

    <Window.Resources>
        <CollectionViewSource x:Key="AnimalsBridge" Source="{Binding Path=Animals}" />

        <CompositeCollection x:Key="AnimalsWithNullItem">
            <local:Animal Id="-1" Name="Pick someone..."/>
            <CollectionContainer Collection="{Binding Source={StaticResource AnimalsBridge}}" />
        </CompositeCollection>
    </Window.Resources>

    <StackPanel>
        <Button Content="Bind" Click="BindComboBox"/>

        <ComboBox x:Name="cmbFavourite"
            SelectedValue="{Binding Path=FavouriteId}"
            SelectedValuePath="Id" DisplayMemberPath="Name"
            ItemsSource="{StaticResource AnimalsWithNullItem}"/>
    </StackPanel>
</Window>
4

1 に答える 1