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

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;
        }
    }
}

但我如何“将其提升到一个水平”呢?所以我可以在后面的代码中绑定到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)
有帮助吗?

解决方案

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

其他提示

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

使用Model-View-ViewModel设计模式 WPF应用程序

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top