簡體   English   中英

WPF從DataGrid更新

[英]WPF Update from datagrid

我在從csv文件填充的WPF中有一個數據網格。 這是使用Linq完成的,並通過CollectionViewSource.Source填充數據網格。

要求是對datagrid中的數據進行的任何更新/更改,然后再保存回csv。

我需要知道如何保存對數據的任何更改嗎? 我一直在玩一些事件和數據上下文,諸如此類,但還沒有任何效果。

抱歉,這是初學者的類型問題。 從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>

謝謝

您可以在單元格結束編輯時監聽事件,然后保存數據源。 例如,在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綁定到它,但是我還沒有足夠使用它來構造適當的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM