简体   繁体   English

WPF:如何在 XAML 中填充我的 ViewModel 而不是背后的代码

[英]WPF: יhow to populate my ViewModel in XAML instead of code behind

So i have this ViewModel class :所以我有这个ViewModel class

public class ViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private ObservableCollection<Person> _persons;

        public ObservableCollection<Person> Porsons
        {
            get { return _persons; }
            set
            {
                _persons = value;
                NotifyPropertyChanged();
            }
        }

        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

And then create this ViewModel class and populate its Person list:然后创建这个ViewModel class并填充它的Person列表:

ViewModel viewModel;
ObservableCollection<Person> persons

public MainWindow()
{
    InitializeComponent();
    viewModel = new ViewModel();
    viewModel.Porsons= persons;
}

And then my ListView :然后我的ListView

<ListView ItemSource={Binding Persons}/>

So instead of binding this Persons list into my ViewModel class and then do this ItemSource can i do it in pure XAML or this is the right way ?因此, ItemSource将此Persons列表绑定到我的ViewModel class ,然后执行此ItemSource我可以在纯XAML执行此操作,还是这是正确的方法?

Instead of creating a ViewModel property on your view it is recommended to use it's DataContext (this link also shows how to set it using XAML) .建议不要在您的视图上创建 ViewModel 属性,而是建议使用它的DataContext(此链接还显示了如何使用 XAML 设置它) Also don't populate the view model in the view since most of the time the data resides in the model and the view should not know anything about any models (when following MVVM).也不要在视图中填充视图模型,因为大多数时间数据驻留在模型中,并且视图不应该知道任何模型的任何信息(在遵循 MVVM 时)。

Please read the link above and visit the links you meet.请阅读上面的链接并访问您遇到的链接。 Also read this article about MVVM .另请阅读有关 MVVM 的这篇文章 This gives you some basic knowledge to make it easier to understand how to use the WPF framework.这为您提供了一些基础知识,使您更容易理解如何使用 WPF 框架。

There are many variations of view model creation in XAML. XAML 中有许多视图模型创建的变体。 For example alternatively you can create it in the App.Xaml to make it globally accessible via the StaticResource markup extension and assign it to the individual controls's DataContext via a Style or use an ObjectDataProvider .例如,您也可以在 App.Xaml 中创建它,以使其可通过StaticResource标记扩展全局访问,并通过Style或使用ObjectDataProvider将其分配给各个控件的DataContext

This example uses XAML Property Element declaration to create a ViewModel instance directly in the target view.此示例使用 XAML 属性元素声明直接在目标视图中创建 ViewModel 实例。 This instance is locally accessible only.此实例只能在本地访问。

ViewModel.cs:视图模型.cs:

namespace Example
{
  public class ViewModel : INotifyPropertyChanged
  {       
    public ViewModel()
    {
      this.Persons = new ObservableCollection<Person>();
    }

    private ObservableCollection<Person> _persons;
    public ObservableCollection<Person> Persons
    {
      get => _persons;
      set
      {
        _persons = value;
        NotifyPropertyChanged();
      }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
      PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
  }
}

View.xaml:查看.xaml:

<Window x:Class="Example.MainWindow"
        ...
        xmlns:local="clr-namespace:Example">

  <Window.DataContext>
    <local:ViewModel />
  </Window.DataContext>

  <Grid>
    <ListView ItemSource={Binding Persons}/>
  </Grid>
</Window>

Yes, you can.是的你可以。 But no, you most certainly do not want to.但不,你肯定不想。

To answer your question, let's say your Person class looks like this:要回答您的问题,假设您的 Person 类如下所示:

public class Person
{
    public string Name { get; set; }
}

You can easily declare a list in XAML and bind it to a ListView (say) like this:您可以轻松地在 XAML 中声明一个列表并将其绑定到 ListView(例如),如下所示:

<ListView DisplayMemberPath="Name">
    <ListView.ItemsSource>
        <x:Array Type="{x:Type vm:Person}">
            <vm:Person Name="Tom" />
            <vm:Person Name="Dick" />
            <vm:Person Name="Harry" />
        </x:Array>
    </ListView.ItemsSource>
</ListView>

The result of which is this:结果是这样的:

在此处输入图片说明

Just because you can do this, though, doesn't mean you should.但是,仅仅因为您可以这样做,并不意味着您应该这样做。 The whole point of MVVM is to separate your view layer from your view model layer. MVVM 的重点是将视图层与视图模型层分开。 You should be able to run your entire application from a test build without creating a single view object at all.您应该能够从测试构建运行整个应用程序,而根本不需要创建单个视图对象。 In asking this question what you are apparently trying to do is declare a data structure in your view layer, which is totally the wrong place to put it.在问这个问题时,您显然试图做的是在您的视图层中声明一个数据结构,这是完全错误的放置位置。 Your view layer should be as "dumb" as possible, with only the weakest possible bindings to your view model layer where the actual logic is going on.你的视图层应该尽可能的“愚蠢”,只有最弱的绑定到你的视图模型层,在那里实际的逻辑正在发生。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 视图模型或XAML代码中的WPF CollectionViewSource - wpf collectionviewsource in viewmodel or xaml code-behind 如何显示第三个中的两个文本框控件内容仅在 WPF 中使用连接 xaml 绑定没有视图模型代码和代码隐藏代码 - How to Show Two textBox control content in third one using concatenating in WPF only in xaml binding no viewmodel code & code behind code 如何在ViewModel中处理Validation.Error而不是我后面的View代码? - How can I handle a Validation.Error in my ViewModel instead of my View's code behind? 如何在没有代码隐藏的情况下处理 ViewModel 中的 WPF 路由命令? - How can I handle WPF routed commands in my ViewModel without code-behind? 在隐藏代码公开的ViewModel上设置子属性的WPF XAML语法是什么? - What is the WPF XAML syntax to set a subproperty on a ViewModel exposed by the code-behind? 如何从 WPF 后面的代码访问 XAML 按钮 - How to access XAML button from code behind WPF 如何使用XAML和后面的代码序列化WPF用户控件 - How can I serialize wpf user control with xaml and code behind WPF:如何将数据从变量后面的代码绑定到xaml中的内容 - WPF: How to bind data from a code behind variable to content in xaml 如何创建模板XAML样式(后面的代码)WPF - How create a template XAML style (code behind) WPF 如何使用XAML绑定到WPF中的父位置更改,并且后面没有代码 - How to bind to parent position changes in WPF using XAML and no code behind
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM