0

我有一个应用程序,我希望在其中拥有一个可以由多个视图模型访问的项目集合的单个实例,其中每个视图模型都与一个视图相关联。为此,我将集合放入应用程序资源中,视图模型在其构造函数中获得对它的引用,并将其作为公共属性提供。

我在视图中有一个 ListBox,它的 DataContext 设置为视图模型,然后它的 ItemsSource 设置为引用应用程序中集合的视图模型属性。然后,ListItems 绑定到集合中项目的属性。

不幸的是,当集合被填充时,ListBox 没有。

这是 App.xaml:

    <Application x:Class="TestBindingToAppResource.App"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:TestBindingToAppResource"
        StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
            </ResourceDictionary.MergedDictionaries>
            <!--Declaring this here so that a single instance of the people list is available to the entire application.-->
            <local:People x:Key="MyPeople"/>
        </ResourceDictionary>
    </Application.Resources>
</Application>

以及单个项目及其集合:

    using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace TestBindingToAppResource
{
    // Contains the data for a single person.
    public class Person : INotifyPropertyChanged
    {
        private string theFirstName;
        public string FirstName { get { return theFirstName; }  set { if (value != theFirstName) { theFirstName = value; NotifyPropertyChanged(); } } }

        private string theLastName;
        public string LastName { get { return theLastName; } set { if (value != theLastName) { theLastName = value; NotifyPropertyChanged(); } } }

        public event PropertyChangedEventHandler PropertyChanged;

        public Person()
        {
            FirstName = "John";
            LastName = "Doe";
        }

        public Person(string firstName, string lastName)
        {
            FirstName = firstName;
            LastName = lastName;
        }

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

    public class People : ObservableCollection<Person>
    {
        public People()
        {

        }
    }
}

主窗口仅包含一个包含列表的 UserControl。

    <Window x:Class="TestBindingToAppResource.MainWindow"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:TestBindingToAppResource"
                Title="MainWindow" Height="350" Width="525">
    <Grid>
        <local:PeopleList x:Name="ListOfPeople"/>
    </Grid>
</Window>

这是包含 ListBox 的 UserControl:

    <UserControl x:Class="TestBindingToAppResource.PeopleList"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:TestBindingToAppResource"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <UserControl.DataContext>
        <local:PeopleViewModel/>
    </UserControl.DataContext>
    <Grid>
        <!--... Other objects ...-->
        <StackPanel Orientation="Vertical" Margin="5,5,5,5">
            <TextBlock Text="Here's a list of people"/>
            <ListBox Name="ListOfPeople" ItemsSource="{Binding People}" Margin="5,0,5,5">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Name="theFirstName" Text="{Binding FirstName}" Margin="5,5,5,5"/>
                            <TextBlock Name="theLastName" Text="{Binding LastName}" Margin="0,5,5,5"/>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
            <!--... Other objects ...-->
        </StackPanel>
        <!--... Other objects ...-->
    </Grid>
</UserControl>

最后,这是将它们联系在一起的视图模型:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace TestBindingToAppResource
{
    // A view model that allows the list in the view to access the people list in the model.

    public class PeopleViewModel
    {
        public People thePeople { get; private set; }

        public PeopleViewModel()
        {
            // A single instance of the people array is instantiated in the Application object as a resource.
            // This allows any number of view models to access a single instance of the data model.

            thePeople = (People)Application.Current.Resources["MyPeople"];

            // The view model should load the people collection.

            LoadThePeople(thePeople);
        }

        private void LoadThePeople (People thePeople)
        {
            thePeople.Add(new Person("Adam", "Baker"));
            thePeople.Add(new Person("Cindy", "Douglas"));
            thePeople.Add(new Person("Edward", "Fox"));
            thePeople.Add(new Person("Gloria", "Herbst"));
        }
    }
}

结果如下:

在此处输入图像描述

所以,我的主要问题当然是,为什么这不起作用?

但是,我相信很多人都有一个相同的目标,即拥有一个数据模型实例,该实例可以被整个应用程序中的多个视图模型访问。这通常是如何完成的?

我在用:

  • WPF
  • C#
  • 赢10
  • VS 2019 社区
4

1 回答 1

0

用户控件的 dataContext 是一个PeopleViewModel实例

<UserControl.DataContext>
    <local:PeopleViewModel/>
</UserControl.DataContext>

然后你将 ListBox 绑定到People属性

<ListBox Name="ListOfPeople" ItemsSource="{Binding People}" Margin="5,0,5,5">

...但 PeopleViewModel 没有People财产,只有thePeople. 所以让它:

<ListBox Name="ListOfPeople" ItemsSource="{Binding thePeople}" Margin="5,0,5,5">

您应该已经People在 Visual Studio 的“输出”窗口中看到有关缺少属性的绑定警告

于 2019-06-23T12:21:46.407 回答