WPF에서 ViewModel에 어떻게 바인딩하고 다양한 XAML 요소가 뷰 모델의 메소드에 바인딩 할 수 있습니까?

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

  •  03-07-2019
  •  | 
  •  

문제

다음과 같은 ListBox를 바인딩 할 수 있습니다.

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 내에서의 바인딩 뒤에있는 코드에서 다양한 방법, 예 : ListBox의 경우 getAll () 및 다른 컨트롤 등의 경우 getBest ()?

뒤의 코드 에서이 구문으로 시도했습니다.

DataContext = new Customers();

그리고 XAML 의이 두 구문은 작동하지 않습니다.

<ListBox ItemsSource="{Binding GetAll}"/> (returns blank ListBox)
<ListBox ItemsSource="{Binding Source={StaticResource GetAll}}"/> (returns error)
도움이 되었습니까?

해결책

사용해야합니다 ObjectDataProvider 방법에 결합하는 것은 표준보다는 예외가되어야합니다. 일반적으로 VM은 모든 관련성을 노출시키는 속성을 포함하여 묶는 속성을 노출합니다. Customer에스.

다른 팁

뷰를 위해보기 모델 클래스 (CustomersViewModel)를 만들어야합니다. CustomersViewModel은 귀하의보기 (ViewCustomers)가 바인딩 할 수있는 속성을 통해 데이터 및 명령 (ICOMMAND 인터페이스)을 노출시킵니다. 그런 다음 ViewCustomer의 DataContext를 CustomersViewModel 인스턴스로 설정할 수 있습니다. WPF의 Model-View-ViewModel 패턴에 대한 다음 MSDN 기사를 확인하십시오.

Model-View-ViewModel 디자인 패턴이있는 WPF 앱

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top