c# - 将可观察集合绑定(bind)到 XAML 中的 ListBox

标签 c# xaml binding listbox observablecollection

我花了很多时间来解决这个问题。

我有一个包含数据的类:

public class User : INotifyPropertyChanged
{
    private int _key;
    private string _fullName;
    private string _nick;

    public int Key
    {
        get{return _key;}
        set { _key = value; NotifyPropertyChanged("Key"); }
    }
    public string Nick
    {
        get { return _nick; }
        set { _nick = value; NotifyPropertyChanged("Nick"); }
    }
    public string FullName
    {
        get { return _fullName; }
        set { _fullName = value; NotifyPropertyChanged("FullName"); }
    }


    public User()
    {
        Nick = "nickname";
        FullName = "fullname";
    }

    public User(String nick, String name, int key)
    {
        Nick = nick;
        FullName  = name;
    }


    //INotifyPropertyChanged implementation
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(String propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public override string ToString() 
    { 
        return string.Format("{0} {1}, {2}", Key, Nick, FullName); 
    }

}

接下来我有一个包含 userClass 类的 observablecollection 的类:

public class UserList : ObservableCollection<UserList>
{
    public UserList (){}

    ~UserList ()
    {
        //Serialize();
    }

    public void Serialize(ObservableCollection<UserList> usersColl) 
    {
        FileStream fs = new FileStream("DataFile.dat", FileMode.Create);
        BinaryFormatter formatter = new BinaryFormatter();
        try
        {
            formatter.Serialize(fs, usersColl);
        }
        catch (SerializationException e)
        {
            Console.WriteLine("Failed to serialize. Reason: " + e.Message);
            throw;
        }
        finally
        {
            fs.Close();
        }
    }

    public void Deserialize() 
    {
        FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
        try 
        {
            BinaryFormatter formatter = new BinaryFormatter();
            //users = (Hashtable) formatter.Deserialize(fs);
            //usersColl = (ObservableCollection<userClass>)formatter.Deserialize(fs);
        }
        catch (SerializationException e) 
        {
            MessageBox.Show(" Error: " + e.Message);
            throw;
        }
        finally 
        {
            fs.Close();
        }
    }

}

事实上,经过大量测试和编辑后,大部分代码无法正常工作,例如序列化。但是数据绑定(bind)不是必需的,绑定(bind)是我现在正在解决的问题。

所以我有这个集合并想将它绑定(bind)到列表框。 我尝试了几种方法,但没有成功。

我尝试的最后一个给了我写入错误:

The resource 'users' cannot be resolved.

<ListBox Grid.Column="0" Name="userViewLeft" ItemsSource="{Binding Source={StaticResource users} }" />

最佳答案

需要注意的几点

  • 使属性公开而不是私有(private)
  • 使变量私有(private)
  • 遵循命名约定,不要在类后面附加 class
  • ItemsSource 您提供的应该是根据数据的范围,在我的示例中是类范围内的用户列表,并且我在 Window Loaded 事件中提供了 ItemSource。

这是一个完整的示例代码,在此我将网格控件嵌套在 ListBox 中,因为稍后您可以更改 VirtualizingStackPanel 的 ListBox 属性。 这样当您对列表进行大量更新时,它会带来巨大的性能提升。 您也可以使用 BindingList,我认为这在性能方面优于 ObservableCollection

用户类:

    public class User : INotifyPropertyChanged
    {
        private int _key;
        private string _fullName;
        private string _nick;

        public int Key
        {
            get { return _key; }
            set { _key = value; NotifyPropertyChanged("Key"); }
        }
        public string NickName
        {
            get { return _nick; }
            set { _nick = value; NotifyPropertyChanged("NickName"); }
        }
        public string Name
        {
            get { return _fullName; }
            set { _fullName = value; NotifyPropertyChanged("Name"); }
        }

        public User(String nick, String name, int key)
        {
            this.NickName = nick;
            this.Name = name;
            this.Key = key; 
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public override string ToString()
        {
            return string.Format("{0} {1}, {2}", Key, NickName, Name);
        }
    }

用户列表类:

    public class Users : ObservableCollection<User>
    {
        public Users()
        {
            Add(new User("Jamy", "James Smith", Count));
            Add(new User("Mairy", "Mary Hayes", Count));
            Add(new User("Dairy", "Dary Wills", Count));
        }
    }

XAML:

   <Grid>
        <Button Content="Start" Height="23" HorizontalAlignment="Left" Margin="416,12,0,0" x:Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
        <ListBox x:Name="UserList" HorizontalContentAlignment="Stretch" Margin="12,41,12,12">
            <ListBox.ItemTemplate>
                <DataTemplate>
                        <Grid Margin="10">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="20" />
                                <ColumnDefinition Width="150" />
                                <ColumnDefinition Width="*" />
                            </Grid.ColumnDefinitions>
                            <TextBlock Text="{Binding Key}" Margin="3" Grid.Column="0" />
                            <TextBlock Text="{Binding NickName}" Margin="3" Grid.Column="1" />
                            <TextBlock Text="{Binding Name}" Margin="3" Grid.Column="2" />
                        </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>

XAML 代码隐藏:

public partial class MainWindow : Window
{
    public static Users userslist = new Users();
    DispatcherTimer timer = new DispatcherTimer();

    public MainWindow()
    {
        InitializeComponent();
        this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
    }

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        timer.Interval = DateTime.Now.AddSeconds(10) - DateTime.Now;
        timer.Tick += new EventHandler(timer_Tick);
        UserList.ItemsSource = userslist;
    }

    void timer_Tick(object sender, EventArgs e)
    {
        userslist.Add(new User("Jamy - " + userslist.Count, "James Smith", userslist.Count));
        userslist.Add(new User("Mairy - " + userslist.Count, "Mary Hayes", userslist.Count));
        userslist.Add(new User("Dairy - " + userslist.Count, "Dary Wills", userslist.Count));
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        if (button1.Content.ToString() == "Start")
        {
            button1.Content = "Stop";
            timer.Start();
        }
        else
        {
            button1.Content = "Start";
            timer.Stop();
        }
    }

}

关于c# - 将可观察集合绑定(bind)到 XAML 中的 ListBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7688193/

相关文章:

c# - 在 DataGrid 上设置 DataContext

c# - 在获取其值之前验证节点是否存在

wpf - 如何仅在XAML中设置自动对焦?

绑定(bind)到服务时出现 Android ClassCast 异常

binding - Emberjs Controller 需要绑定(bind)

c# - 使用 linq 连接两个表,并填充它们的字典

c# - ListView HasUnEvenRows 不工作

c# - WPF 控件模板 - 如何创建自定义属性?

c# - 如何在解决方案中的项目之间共享单个配置?

wpf - 将多重绑定(bind)放在 xaml 中的一行上