在WPF中,如何绑定到ViewModel并将各种XAML元素绑定到ViewModel的方法?

时间:2009-04-29 11:17:22

标签: c# wpf data-binding xaml

我可以像这样绑定一个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;
        }
    }
}

但是我如何“将其提升到一个级别”,这样我就可以在代码中绑定到Customers本身,并在我的XAML中绑定到Customers各种方法,例如ListBox的GetAll()和另一个控件的GetBest()等?

我在后面的代码中尝试了这种语法:

DataContext = new Customers();

这两个语法在XAML中但都不起作用:

<ListBox ItemsSource="{Binding GetAll}"/> (returns blank ListBox)
<ListBox ItemsSource="{Binding Source={StaticResource GetAll}}"/> (returns error)

2 个答案:

答案 0 :(得分:4)

您需要使用ObjectDataProvider绑定到方法,但这应该是例外而不是常态。通常,您的VM只会公开您绑定的属性,包括公开所有相关Customer的属性。

答案 1 :(得分:1)

您需要为视图创建视图模型类(CustomersViewModel)。 CustomersViewModel将通过您的视图(ViewCustomers)可以绑定的属性公开数据和命令(ICommand接口)。然后,您可以将ViewCustomers的DataContext设置为CustomersViewModel的实例。 查看以下有关WPF中Model-View-ViewModel模式的MSDN文章。

WPF Apps With The Model-View-ViewModel Design Pattern