【问题标题】:In WPF how can I bind to the ViewModel and have various XAML elements bind to the ViewModel's methods?在 WPF 中,如何绑定到 ViewModel 并将各种 XAML 元素绑定到 ViewModel 的方法?
【发布时间】:2023-03-31 19:15:01
【问题描述】:

我可以像这样绑定 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)

【问题讨论】:

    标签: c# wpf data-binding xaml


    【解决方案1】:

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

    【讨论】:

    • 我认为 ObjectDataProvider 是要避免的,此外它似乎不在 Silverlight 中,所以我想在没有它的情况下降低一些模式,所以我把它拿出来,将我的 V 绑定到我的虚拟机,暴露数据,绑定数据,但没有显示出来:stackoverflow.com/questions/802162/…
    【解决方案2】:

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

    WPF Apps With The Model-View-ViewModel Design Pattern

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-23
      • 1970-01-01
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 2015-07-04
      • 2014-03-28
      相关资源
      最近更新 更多