web-dev-qa-db-ja.com

wpfコンボボックスバインディング

こんにちは私はリスト<>をコンボボックスにバインドしようとしています。

<ComboBox Margin="131,242,275,33" x:Name="customer" Width="194" Height="25"/>

public OfferEditPage()
    {
        InitializeComponent();
        cusmo = new CustomerViewModel();
        DataContext = this;
        Cusco = cusmo.Customer.ToList<Customer>();
        customer.ItemsSource = Cusco;
        customer.DisplayMemberPath = "name";
        customer.SelectedValuePath = "customerID";
        customer.SelectedValue = "1";
    }

エラーは発生しませんが、コンボボックスは常に空です。クスコは私のリストの所有物です。このコードの何が問題なのかわかりません。手伝って頂けますか?

挨拶

 public class Customer
{
    public int customerID { get; set; }
    public string name { get; set; }
    public string surname { get; set; }
    public string telnr { get; set; }
    public string email { get; set; }
    public string adress { get; set; }
}

これが私のモデルであるカスタマークラスです。

public class CustomerViewModel
{
    private ObservableCollection<Customer> _customer;

    public ObservableCollection<Customer> Customer
    {
        get { return _customer; }
        set { _customer = value; }
    }

    public CustomerViewModel()
    {
        GetCustomerCollection();
    }

    private void GetCustomerCollection()
    {
        Customer = new ObservableCollection<Customer>(BusinessLayer.getCustomerDataSet());
    }

}

これがViewModelです。

8
Veeesss

実際のBindingオブジェクトを使用してItemsSourceプロパティを設定してみてください

XAMLメソッド(推奨):

<ComboBox
    ItemsSource="{Binding Customer}"
    SelectedValue="{Binding someViewModelProperty}"
    DisplayMemberPath="name"
    SelectedValuePath="customerID"/>

プログラムによる方法:

Binding myBinding = new Binding("Name");
myBinding.Source = cusmo.Customer; // data source from your example

customer.DisplayMemberPath = "name";
customer.SelectedValuePath = "customerID";
customer.SetBinding(ComboBox.ItemsSourceProperty, myBinding);

また、CustomerプロパティのセッターはPropertyChangedイベントを発生させる必要があります

public ObservableCollection<Customer> Customer
{
    get { return _customer; }
    set
    {
        _customer = value;
        RaisePropertyChanged("Customer");
    }
}

上記が機能しない場合は、バインディング部分をコンストラクターからOnLoadedオーバーライドメソッドに移動してみてください。ページが読み込まれると、値がリセットされる可能性があります。

23
Steve Konves

スティーブの答えの拡張として、

フォームのデータコンテキストを設定する必要があります。

現在あなたはこれを持っています:

InitializeComponent();
cusmo = new CustomerViewModel();
DataContext = this;

これに変更する必要があります:

InitializeComponent();
cusmo = new CustomerViewModel();
DataContext = cusmo;

次に、Steveが指摘したように、選択したアイテムを格納するには、ビューモデルに別のプロパティが必要になります。

3
klaverty