简体   繁体   English

MVVM WPF数据绑定问题

[英]MVVM WPF Data Binding issue

I am new to MVVM and WPF, I have the below model which I want to show it to user using the data binding (Code for viewmodel and xaml is also provided below). 我是MVVM和WPF的新手,我有以下模型,希望通过数据绑定向用户展示(下面也提供了viewmodel和xaml的代码)。 But I am not sure what is missing, because the list of users are not being shown on UI at all. 但是我不确定缺少什么,因为用户列表根本没有显示在UI上。 Can anyone tell me which I am missing from my code?! 谁能告诉我代码中我缺少哪一个?

If instead Class of Users, I use a List from class User: 如果不是用户类,则使用用户类中的列表:

  private List<User> _UsersList;
        public List<User> users
        {
            get { return _UsersList; }
            set { _UsersList = value; }
        }

, then the biding works!, but if I use Users class, the binding does not work! ,则出价有效!!但如果使用Users类,则绑定无效!

Model: 模型:

 public class User : ObservableObject
 {

        public int ID { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public bool IsPremiumUser { get; set; }
        public string selectedItem { get; set; }
        public string SelectedValue
        {
            get { return selectedItem; }
            set
            {
                selectedItem = value;
                //  suser.age = Convert.ToInt32(value);
                RaisePropertyChangedEvent("SelectedValue");
            }

        }
        public int[] myItem { get; set; }
        public int[] UserItems
        {
            get { return myItem; }
            set { myItem = value; }
        }
        private SelectedUser suser = new SelectedUser();
        public int selected { get; set; }
        public int Selected
        {
            get { return selected; }
            set
            {
                selected = value;
                suser.age = Convert.ToInt32(value);
                RaisePropertyChangedEvent("Selected");
            }

        }
    }
   public class Users : ObservableObject
    {
        private List<User> mylist = new List<User>();
        private List<User> list
        {
            get { return mylist; }
            set
            {
                mylist = value;

            }
        }
        public void Add(User user)
        {
            this.list.Add(user);
        }

        public User GetById(int id)
        {
            return this.list.First(u => u.ID == id);
        }

    }

ViewModel: ViewModel:

 public class ViewModel : ObservableObject
 {

        public ViewModel()
        {
            users = new Users();
            for (int i = 0; i < 100000; ++i)
            {
                int[] numbers;
                numbers = new int[3] { 1, 2, 3 };
                var user = new User { ID = i, Name = "Name " + i.ToString(), Age = 20 + i, UserItems = numbers, SelectedValue = "0" };
                if (i == 2 || i == 4)
                {
                    user.IsPremiumUser = true;
                }
                users.Add(user);
            }

        }
        private Users _UsersList;
        public Users users
        {
            get { return _UsersList; }
            set { _UsersList = value; }
        }

        private int _currenuser;
        public int CurrentUser
        {
            get
            {
                return _currenuser;
            }
            set
            {
                _currenuser = value;

                RaisePropertyChangedEvent("CurrentUser");
            }
        }
    }

XAML: XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        Icon="C:\Users\maninx2\Documents\Visual Studio 2013\Projects\SampleFormMaker1\WpfApplication1\abbott_point_of_care_HuT_icon.ico"
        Title="MainWindow" Height="700" Width="1249.129">
    <Window.Resources>
        <DataTemplate x:Key="NormalUserDataTemplate">
            <StackPanel>
                <TextBlock Text="{Binding Name}" />
                <TextBox Text="{Binding SelectedValue, UpdateSourceTrigger=PropertyChanged}" Width="300" />

            </StackPanel>
        </DataTemplate>
        <DataTemplate x:Key="PremiumUserDataTemplate">
            <StackPanel Background="LightBlue">
                <ComboBox  SelectedIndex="{Binding SelectedValue, UpdateSourceTrigger=PropertyChanged}" Text="{Binding Name}"  Width="300" ItemsSource="{Binding UserItems}"/>

            </StackPanel>
        </DataTemplate>
        <local:PremiumUserDataTemplateSelector x:Key="myPremiumUserDataTemplateSelector" />
    </Window.Resources>
    <TabControl Name="TabControl1">
        <TabControl.ItemContainerStyle>
            <Style TargetType="{x:Type TabItem}">
                <Setter Property="Visibility" Value="Collapsed"/>
            </Style>
        </TabControl.ItemContainerStyle>
        <TabItem Header="General">
            <ScrollViewer VerticalScrollBarVisibility="Auto">
                <StackPanel Height="800" Orientation="Horizontal" >
                    <ListView x:Name="myListView" ItemsSource="{Binding users,  Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ItemTemplateSelector="{StaticResource myPremiumUserDataTemplateSelector}" SelectedIndex="{Binding CurrentUser, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
                    </ListView>
                    <ListView x:Name="myListView1" ItemsSource="{Binding users,  Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"   HorizontalAlignment="Stretch" >
                        <ListView.View>
                            <GridView>
                                <GridViewColumn Width="140" Header="Selected Values"
                 DisplayMemberBinding="{Binding SelectedValue}"  />

                            </GridView>
                        </ListView.View>
                    </ListView>
                    <Button Content="Next"
        HorizontalAlignment="Left"
        Margin="10,10,0,0"
        VerticalAlignment="Top"
        Width="75"
        Click="Button_Click"/>
                </StackPanel>

            </ScrollViewer>

        </TabItem>
        <TabItem Header="Second Tab">
            <StackPanel>
                <TextBlock Name="lbl1" Text="{Binding CurrentUser, UpdateSourceTrigger=PropertyChanged}"/>

            <Button Content="Previous"
        HorizontalAlignment="Left"
        Margin="10,10,0,0"
        VerticalAlignment="Top"
        Width="75"
        Click="Button_Click1"/>
            </StackPanel>
        </TabItem>

    </TabControl>

</Window>

You are missing inheriting the Users from ObservableCollection. 您缺少从ObservableCollection继承用户的信息。 So, WPF engine does not know how to get the data from this class. 因此,WPF引擎不知道如何从此类中获取数据。

Update: 更新:

@user3033921: You inherited it from ObservableObject not ObservableCollection. @ user3033921:您从ObservableObject继承了它,而不是ObservableCollection。 So, the thing is if you want this class to be recognized from as a list then you would have to get that class inherited by an ICollection object and if you want that class to be observable it should be implementing both ICollection and INotifyPropertyChange. 因此,事情是,如果您希望将该类从列表中识别出来,则必须让该类被ICollection对象继承,并且如果您希望该类是可观察的,则应同时实现ICollection和INotifyPropertyChange。 So, to @BradleyDotNet's point if you dont have any specific reason to create your own type, then just create a object of users with type ObservableCollection. 因此,@ BradleyDotNet的观点是,如果您没有创建自己的类型的特定原因,则只需创建一个ObservableCollection类型的用户对象即可。 If you have a specific need to have a type Users then you can derive it from ObserableCollection as recommended solution. 如果您特别需要具有用户类型,则可以从ObserableCollection派生它作为推荐的解决方案。 But keep in mind you do not want to have List in the Users class anymore as your class is now by itself is a list. 但是请记住,您现在不想再在Users类中使用List,因为您的类现在本身就是一个列表。 So, if you have any specific implementation to do like GetByID, then the class would look like: 因此,如果您有任何特定的实现(例如GetByID),则该类将如下所示:

public class Users :ObservableCollection<User>
{
    public User GetById(int id)
    {
        return this.First(u => u.ID == id);
    }

}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM