ObservableCollection-Binding-Demo

在这里插入图片描述
.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace WpfApplication6
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        ObservableCollection<Test> tests = new ObservableCollection<Test>();
        public MainWindow()
        {
            InitializeComponent();
            
            tests.Add(new Test() { Name = "j1", Age = 31 });
            tests.Add(new Test() { Name = "j2", Age=  32 });
            tests.Add(new Test() { Name = "j3", Age = 33 });
            this.ListBox.ItemsSource = tests;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (sender == this.AddButton)
            {
                tests.Add(new Test() { Name = "jas1", Age = 331 });
            }
            else
            {
                tests.Remove((Test) this.ListBox.SelectedItem);
            }
        }
    }
    class Test
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}


.xaml

<Window x:Class="WpfApplication6.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        xmlns:LocalWindow="clr-namespace:WpfApplication6"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <ListBox x:Name ="ListBox" DisplayMemberPath="Name"  Height="80" ScrollViewer.HorizontalScrollBarVisibility="Auto"/>
        <!--附加属性ScrollViewer-->
        <Button  x:Name ="AddButton" Margin="30" Height="20" Click="Button_Click" Content="+"/>
        <Button  x:Name ="SubButton" Margin="30" Height="20" Click="Button_Click" Content="-"/>
    </StackPanel>
</Window>


猜你喜欢

转载自blog.csdn.net/qq_37627370/article/details/83583206
今日推荐