MVVM WPF数据绑定问题

本文关键字:问题 数据绑定 WPF MVVM | 更新日期: 2023-09-27 18:13:53

我是MVVM和WPF的新手,我有下面的模型,我想用数据绑定向用户展示它(下面还提供了viewmodel和xaml的代码)。但我不确定缺少什么,因为用户列表根本没有显示在UI上。谁能告诉我,我从我的代码失踪?!

如果使用Class of Users,则使用来自Class User的List:

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

,那么投标工作!,但如果我使用Users类,绑定不起作用!

模型:

 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:

 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:

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

MVVM WPF数据绑定问题

您没有从ObservableCollection继承Users。因此,WPF引擎不知道如何从这个类中获取数据。

更新:

@user3033921:你从ObservableObject而不是ObservableCollection继承了它。问题是,如果你想要这个类被识别为一个列表那么你需要让那个类被一个ICollection对象继承如果你想要那个类是可观察的它应该同时实现ICollection和INotifyPropertyChange。所以,按照@BradleyDotNet的观点,如果你没有任何特殊的理由来创建你自己的类型,那么就创建一个类型为ObservableCollection的用户对象。如果你有一个特定的需要有一个类型Users,那么你可以从ObserableCollection作为推荐的解决方案派生它。但请记住,您不想在Users类中再拥有List,因为您的类现在本身就是一个列表。所以,如果你有任何特定的实现,比如GetByID,那么这个类应该是这样的:

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