54.DataGrid数据框图 C#例子 WPF例子

首先是绑定一个属性,属性名称无所谓。到时候看属性设置的啥,可能要改。

<DataGrid ItemsSource="{Binding Index_instance}"/>

然后创建INotifyPropertyChanged的类,并把相关固定的代码粘贴上去。

然后把这个目录类建好,要用

    public class Index1
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Status { get; set; }


    }

用这个目录类创建属性

 private ObservableCollection<Index1> _index_instance;
        public ObservableCollection<Index1> Index_instance
        {
            get { return _index_instance; }
            set
            {
                _index_instance = value;
                OnPropertyChanged(nameof(Index_instance));
            }
        }

再创建构造函数,搞三个实例,并赋值。

        public Notify()
        {
            Index_instance = new ObservableCollection<Index1>
            {
                new Index1() {Id= 1, Name="Test 1", Status="Active" },
                new Index1() {Id= 2, Name="Test 2", Status="Inactive" },
                new Index1() {Id= 3, Name="Test 3", Status="Bad" },
            };

        }

最后一步,把窗口资源导向这个类的实例

DataContext = new Notify();

后台代码:

主窗口后台使用DataContext = new Notify();对应的类名称来引入自己定义的类里面的属性。

在VieModel中

class ViewModel:INotifyPropertyChanged
{
    private ObservableCollection<Index1> _dataGridSource;
    public ObservableCollection<Index1> DataGridSource
    {
        get { return _dataGridSource; }
        set 
        { 
            _dataGridSource = value;
            OnPropertyChanged(nameof(DataGridSource));
        }
    }

    public ViewModel()
    {
        _dataGridSource = new ObservableCollection<Index1>
        {
            new Index1(){Id=1,Name="Alic",Description="Active"}, 
            new Index1(){Id=2,Name="Baliy",Description="Inactive"},
            new Index1(){Id=3,Name="Cecy",Description="Down"},

        };
    }


    //固定部分
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }


}
public class Index1
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

XAML部分:

<Window x:Class="DataGrid练习2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DataGrid练习2"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <DataGrid Margin="30" ItemsSource="{Binding DataGridSource}"/>
    </Grid>
</Window>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值