WPFでは、どのようにしてViewModelにバインドし、さまざまなXAML要素をViewModelのメソッドにバインドできますか?

StackOverflow https://stackoverflow.com/questions/801889

  •  03-07-2019
  •  | 
  •  

質問

次のようにリストボックスをバインドできます:

XAML:

<UserControl x:Class="TestDynamicForm123.Views.ViewCustomers"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel Margin="10">
        <ListBox ItemsSource="{Binding}"/>
    </StackPanel>
</UserControl>

コードビハインド:

using System.Windows.Controls;
using TestDynamicForm123.ItemTypes;

namespace TestDynamicForm123.Views
{
    public partial class ViewCustomers : UserControl
    {
        public ViewCustomers()
        {
            InitializeComponent();

            DataContext = Customers.GetAll();
        }
    }
}

モデルの表示:

using System.Collections.ObjectModel;

namespace TestDynamicForm123.ItemTypes
{
    class Customers : ItemTypes
    {
        protected ObservableCollection<Customer> collection;

        public static ObservableCollection<Customer> GetAll()
        {
            ObservableCollection<Customer> customers = new ObservableCollection<Customer>();
            customers.Add(new Customer() { FirstName = "Jay", LastName = "Anders", Age = 34 });
            customers.Add(new Customer() { FirstName = "Jim", LastName = "Smith", Age = 23 });
            customers.Add(new Customer() { FirstName = "John", LastName = "Jones", Age = 22 });
            customers.Add(new Customer() { FirstName = "Sue", LastName = "Anders", Age = 21 });
            customers.Add(new Customer() { FirstName = "Chet", LastName = "Rogers", Age = 35 });
            customers.Add(new Customer() { FirstName = "James", LastName = "Anders", Age = 37 });
            return customers;
        }
    }
}

しかし、「レベルを上げる」方法は?そのため、顧客自身にバインドするコードの背後で、XAMLで顧客にさまざまな方法でバインドすることができます。リストボックスの場合はGetAll()、別のコントロールの場合はGetBest()など?

コードビハインドでこの構文を使用して試しました:

DataContext = new Customers();

XAMLのこれら2つの構文は機能しますが、どちらも機能しません:

<ListBox ItemsSource="{Binding GetAll}"/> (returns blank ListBox)
<ListBox ItemsSource="{Binding Source={StaticResource GetAll}}"/> (returns error)
役に立ちましたか?

解決

ObjectDataProvider <を使用する必要があります/ code> を使用してメソッドにバインドしますが、これは標準ではなく例外です。通常、VMは、関連するすべての Customer を公開するプロパティなど、バインドするプロパティを公開するだけです。

他のヒント

ビューのビューモデルクラス(CustomersViewModel)を作成する必要があります。 CustomersViewModelは、ビュー(ViewCustomers)がバインドできるプロパティを介してデータとコマンド(ICommandインターフェイス)を公開します。その後、ViewCustomersのDataContextをCustomersViewModelのインスタンスに設定できます。 WPFのModel-View-ViewModelパターンに関する次のMSDN記事をご覧ください。

Model-View-ViewModelデザインパターンを使用したWPFアプリ

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top