1

私はこのコンボボックスを持っています

<ComboBox  Height="30" SelectedIndex="0" Margin="5 3 5 3" Width="170" ItemsSource="{Binding WonderList}" SelectedValuePath="selectedWonder">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <WrapPanel>
                <Image Source="{Binding Path}" Height="20"></Image>
                <Label Content="{Binding Name}" Style="{StaticResource LabelComboItem}"></Label>
            </WrapPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

アイテムを画像とテキストとして表示したい場所。

これは、アイテム リスト内のオブジェクトのビジネス クラスです。

public class Wonder: INotifyPropertyChanged
{
    private string name;
    private string path;
    public event PropertyChangedEventHandler PropertyChanged;

    #region properties, getters and setters
    public String Name { get; set; }
    public String Path { get; set; }
    #endregion

    public Wonder(string name, string path)
    {
        this.name = name;
        this.path = path;
    }

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

およびウィンドウの背後にあるコード

public class Window1 {
    public List<Wonder> WonderList;

    public Window1()
    {
        InitializeComponent();
        WonderList = new List<Wonder>();
        WonderList.Add(new Wonder("Alexandria", "Resources/Images/Scans/Wonders/Alexandria.jpg"));
        WonderList.Add(new Wonder("Babylon", "Resources/Images/Scans/Wonders/Babylon.jpg"));
    }
}

私はこのxamlの「魔法」にかなり慣れていないので、データバインディングがどのように機能するかを正しく理解していないと思います. ItemsSource="{Binding WonderList}"(コードビハインドから)その名前のコレクションを取得し、それらの名前とパスを表示する必要があると思いますが、空のリストを示します。

コード ビハインドで行う場合Combo1.ItemsSource = WonderList;(xaml を使用し、コード ビハインドを回避することを好みます)、2 つの空白スロットが表示されますが、項目を表示する方法がわかりません。

正しい方向に私を向けることができますか?

ありがとう

4

2 に答える 2

3

このようにバインドしたい場合は、最初ItemsSource="{Binding WonderList}"に設定する必要があります。DataContext

public Window1()
{
    ...
    this.DataContext = this;
}

次に、Binding は Window1 で WonderList を見つけますが、それがプロパティでもある場合のみです。

public List<Wonder> WonderList { get; private set; }

次: 値をプライベート フィールド name に代入する場合、プロパティ Name にバインドしても意味がありません。コンストラクターを次のように置き換えます

public Wonder(string name, string path)
{
    this.Name = name;
    this.Path = path;
}

次へ: 自動プロパティ ( { get; set; }) は変更を通知しません。このためにはOnPropertyChanged、setter を呼び出す必要があります。例えば

public String Name
{
    get { return name; }
    set
    {
        if (name == value) return;
        name = value;
        OnPropertyChanged("Name");
    }
}

WonderList についても同じことが言えます。コンストラクターの後半にリストを作成すると、すべてのバインディングが既に解決されていて、何も表示されない可能性があります。

最後ObservableCollectionに、新しいリストではなく、リストに新しく追加されたアイテムについて通知したい場合に使用します。

于 2013-06-23T22:28:53.867 に答える