Wpf DataGrid动态添加列,行数据(一)


由于最近有这方面的需求,而且刚接触wpf不久,在网上找了很多方法,都不是使用MVVM模式的,因为DataGrid的列不能绑定

这就难受了,我想了个折中的方法,这个是使用了MVVMLight的消息机制,我就不说太多了,直接上代码

UI界面

<Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>

        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"></RowDefinition>

            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal">
            <Button Content="新增列" Command="{Binding AddColumnCmd}" Margin="5"/>
            <Button Content="删除列" Command="{Binding DeleteColumnCmd}" Margin="5"/>
            <Button Content="新增数据" Command="{Binding AddDataCmd}" Margin="5"/>
        </StackPanel>
        <DataGrid x:Name="dataGrid" AutoGenerateColumns="True" Grid.Row="1" SelectionUnit="Cell" SelectionMode="Extended"/>
    </Grid>

  这里需要在

 

 

 这里发一个消息,MessageToken如下:其实就是一个字符串类,防止重复

public class MessageToken
    {
        /// <summary>
        /// 设置DataGrid消息
        /// </summary>
        public static readonly string SetDataGrid = nameof(SetDataGrid);
    }

ViewModel

 public class MainViewModel : ViewModelBase
    {
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.  DataGrid
        /// </summary>
        public MainViewModel()
        {
            //注册设置vm里的DataGrid与界面的相关联
            Messenger.Default.Register<DataGrid>(this, MessageToken.SetDataGrid, (x) =>
            {
                DDataGrid = x;

                for (int i = 0; i < 5; i++)
                {
                    dynamic item = new ExpandoObject();
                    item.A = "Property A value - " + i.ToString();
                    item.B = "Property B value - " + i.ToString();
                    _Items.Add(item);
                }

                DDataGrid.Columns.Add(new DataGridTextColumn() { Header = "A", Binding = new Binding("A") });
                DDataGrid.Columns.Add(new DataGridTextColumn() { Header = "B", Binding = new Binding("B") });
                DDataGrid.ItemsSource = _Items;
            });

           
        }
        /// <summary>
        /// 绑定的数据
        /// </summary>
        ObservableCollection<ExpandoObject> _Items = new ObservableCollection<ExpandoObject>();

        public DataGrid DDataGrid;

        public ObservableCollection<ExpandoObject> Items
        {
            get { return _Items; }
            set
            {
                _Items = value;
                RaisePropertyChanged(()=> Items);
            }
        }


        public RelayCommand AddColumnCmd => new Lazy<RelayCommand>(() =>
           new RelayCommand(AddColumn)).Value;
        public RelayCommand AddDataCmd => new Lazy<RelayCommand>(() =>
            new RelayCommand(AddData)).Value;
        public RelayCommand DeleteColumnCmd => new Lazy<RelayCommand>(() =>
            new RelayCommand(DeleteColumn)).Value;

        private void AddData()
        {
            dynamic item = new ExpandoObject();
            item.A = "New Item - A";
            item.B = "New Item - B";
            item.NewColumn1 = "New Item - C";
            Items.Add(item);
        }

        int newColumnIndex = 1;
        private void AddColumn()
        {
            foreach (IDictionary<String, Object> item in Items)
            {
                item.Add("NewColumn" + newColumnIndex, "New Column Value - " + newColumnIndex.ToString());
            }

            DDataGrid.Columns.Add(new DataGridTextColumn() { Header = "NewColumn" + newColumnIndex, Binding = new Binding("NewColumn" + newColumnIndex) });

            newColumnIndex++;
        }

        private void DeleteColumn()
        {
            for (int i = 0; i < DDataGrid.SelectedCells.Count; i++)
            {
                //DataRowView Row = (DataRowView)DDataGrid.SelectedCells[i].Item;
                //string result = Row[DDataGrid.SelectedCells[i].Column.DisplayIndex].ToString();

                //string result = DDataGrid.SelectedCells[i].Column.DisplayIndex.ToString();
                
                DDataGrid.Columns.Remove(DDataGrid.SelectedCells[i].Column);
            }
        }
    }

记得在界面上绑定MainViewModel

运行效果

 

 删除B列

 

 我在尝试不用消息的方式,直接绑定,成功再发。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2020 CODEPRJ.COM