来自datagrid的WPF更新

时间:2010-07-17 13:25:34

标签: c# wpf datagrid

我在从csv文件填充的WPF中有一个数据网格。 这是通过Linq完成的,并通过CollectionViewSource.Source填充数据网格。

要求是对数据网格中的数据进行的任何更新/更改然后保存回csv。

我需要知道如何保存对数据的任何更改?我一直在玩一些事件和datacontext等等,但还没有任何效果。

如果这是初学者的类型问题,我道歉。从Windows应用程序迁移到WPF是一个陡峭的学习曲线(至少对我而言)。 我现在只是从阵列填充,而我试图弄明白。基本上只是想再次取出数据,保存为var。

  System.Windows.Data.CollectionViewSource personViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("personViewSource")));

        List<Person> T = new List<Person>();
          Person p = new Person();

          string[] str = new string[] { "Stacey", "Olivia", "Dylan", "Lauryn", "Beth", "Caitlin" };
          var data = from s in str
                     select s;
          Person pers;
          foreach (var d in data)
          {
              pers = new Person();
              pers.Name = d;
              pers.Age = 22;
              T.Add(pers);
          }


        personViewSource.Source = T;

xaml:

<Window x:Class="WpfApplication4.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded" Name="win1" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:my="clr-namespace:WpfApplication4">
<Window.Resources>
    <CollectionViewSource x:Key="personViewSource" d:DesignSource="{d:DesignInstance my:Person, CreateList=True}" />
</Window.Resources>
<StackPanel Width="369" Height="230" DataContext="{StaticResource personViewSource}">
    <DataGrid AutoGenerateColumns="False" EnableRowVirtualization="True" ItemsSource="{Binding}" Name="personDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" Width="88" HorizontalAlignment="Left" BorderThickness="4" Background="#FFF8C5C5" SelectionChanged="personDataGrid_SelectionChanged" TextInput="personDataGrid_TextInput" RowEditEnding="personDataGrid_RowEditEnding" TargetUpdated="personDataGrid_TargetUpdated">
        <DataGrid.Columns>
            <DataGridTextColumn x:Name="nameColumn" Binding="{Binding Path=Name, Mode=TwoWay, NotifyOnTargetUpdated=True}" Header="Name" Width="SizeToHeader" />
            <DataGridTextColumn x:Name="ageColumn" Binding="{Binding Path=Age}" Header="Age" Width="SizeToHeader" Foreground="#FFC14040" />
        </DataGrid.Columns>
    </DataGrid>
</StackPanel>

由于

1 个答案:

答案 0 :(得分:1)

您可以在单元结束编辑时监听事件,然后保存数据源。即,在InitializeComponent()调用之后将它放在托管网格的控件的构造函数中(可能是用户控件,窗口,页面等)

   this.myDataGrid.CellEditEnding += new EventHandler<DataGridCellEditEndingEventArgs>(grid_CellEditEnding);

然后让处理程序保存数据源

  void grid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) {
     //save my data source
  }

我个人更喜欢你可以执行编辑然后在最后点击保存的方法,但在你的情况下,你可以使用String.Join创建一个CSV字符串,然后将其写入文件。

为此,请创建一个属性列表,以便为网格构建数据:

public Collection<Person> MyPersonDataSource {get; private set; }

public MyWindowsConstructor() {
    //build the grid data before you initialize the window, as the PersonDataSource
    //does not implement NotifyPropertyChanged, if you build the data afterwards
    //the binding won't be updated
    BuildGridData();
    InitializeComponent();
} 


private void BuildGridData(){

  this.MyPersonDataSource = new Collection<Person>();
  Person p = new Person();

  string[] str = new string[] { "Stacey", "Olivia", "Dylan", "Lauryn", "Beth", "Caitlin" };
  var data = from s in str
             select s;
  Person pers;
  foreach (var d in data)
  {
     pers = new Person();
     pers.Name = d;
     pers.Age = 22;
     this.MyPersonDataSource.Add(pers);
  }
}

然后在你的单元格结束编辑功能

  void grid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) {
     //save my data source
     var nameArray = this.MyPersonDataSource.Select(item => item.Name).ToArray();
     //create the csv string
     String csvString = String.Join("," nameArray);
     //write it to a file
     System.IO.File.WriteAllText(@"C:\SomeFolderYouHavePermissionsOn\names.csv", csvString);
  }

我会将我的网格直接绑定到属性MyPersonDataSource,就像这样..

<Window x:Class="WpfApplication4.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded" Name="win1" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:my="clr-namespace:WpfApplication4">
<Window.Resources>
    <CollectionViewSource x:Key="personViewSource" Source="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=MyPersonDataSource}" d:DesignSource="{d:DesignInstance my:Person, CreateList=True}" />
</Window.Resources>
<StackPanel Width="369" Height="230" DataContext="{StaticResource personViewSource}">
    <DataGrid AutoGenerateColumns="False" EnableRowVirtualization="True" ItemsSource="{Binding}" Name="personDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" Width="88" HorizontalAlignment="Left" BorderThickness="4" Background="#FFF8C5C5" SelectionChanged="personDataGrid_SelectionChanged" TextInput="personDataGrid_TextInput" RowEditEnding="personDataGrid_RowEditEnding" TargetUpdated="personDataGrid_TargetUpdated">
        <DataGrid.Columns>
            <DataGridTextColumn x:Name="nameColumn" Binding="{Binding Path=Name, Mode=TwoWay, NotifyOnTargetUpdated=True}" Header="Name" Width="SizeToHeader" />
            <DataGridTextColumn x:Name="ageColumn" Binding="{Binding Path=Age}" Header="Age" Width="SizeToHeader" Foreground="#FFC14040" />
        </DataGrid.Columns>
    </DataGrid>
</StackPanel>
</Window>

我可能会考虑比CSV更强大的数据存储,你可以使用xml并使用XPath绑定它,但我还没有使用它来构建一个合适的答案。