[英]No data flows from data grid to Observable Collection after hitting a button
I am using Editable Datagrid in WPF, when ever i edit the grid like creating new records and hitting a button say for example create button, Then data from my data grid flows properly to the Observable Collection in code behind.cs file.我在 WPF 中使用可编辑数据网格,当我编辑网格时,例如创建新记录并点击按钮,例如创建按钮,然后我的数据网格中的数据正确流向代码 behind.cs 文件中的可观察集合。 But when i load data to my grid with an excel upload and clicked the create button, then there is no data available in the Observable Collection in code behind.但是,当我使用 excel 上传将数据加载到我的网格并单击创建按钮时,后面的代码中的 Observable Collection 中没有可用的数据。 Its weird.有点奇怪。 Need some help.需要一些帮助。 Find my code samples below在下面找到我的代码示例
Data grid in XAML: XAML 中的数据网格:
<DataGrid x:Name="bulkGroupCreationDataGrid" ItemsSource="{Binding BulkGroupCreationModel}" ContextMenuOpening="TheGrid_ContextMenuOpening"
Height="300" CanUserAddRows="True" CanUserDeleteRows="True" CanUserResizeColumns="True" IsManipulationEnabled="True" AutoGenerateColumns="False" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" SelectionChanged="bulkGroupCreationDataGrid_SelectionChanged_1">
<DataGrid.Columns>
<DataGridTextColumn Width="100" Header="Group" Binding="{Binding Group, ValidatesOnExceptions=True}" />
<DataGridComboBoxColumn Header="Scope" Width="100" x:Name="Scope"
SelectedValueBinding="{Binding Scope, Mode=TwoWay}"
DisplayMemberPath="{Binding Scope}"/>
<DataGridComboBoxColumn Header="Type" Width="100" x:Name="GroupType"
SelectedValueBinding="{Binding GroupType, Mode=TwoWay}"
DisplayMemberPath="{Binding GroupType}"/>
<DataGridTextColumn Width="100" Header="Description" Binding="{Binding Description, ValidatesOnExceptions=True}" />
<DataGridTextColumn Width="70" Header="OU" Binding="{Binding OU, ValidatesOnExceptions=True}" />
<DataGridTextColumn Width="70" Header="Sub-OU" Binding="{Binding SubOU, ValidatesOnExceptions=True}" />
</DataGrid.Columns>
<DataGrid.CommandBindings>
<CommandBinding Command="{x:Static ApplicationCommands.Paste}"
CanExecute="CanPaste" Executed="Paste"/>
<CommandBinding Command="{x:Static ApplicationCommands.New}"
CanExecute="CanAddNew" Executed="AddNew"/>
</DataGrid.CommandBindings>
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Command="{x:Static ApplicationCommands.Paste}" Header="Paste"/>
<MenuItem Command="{x:Static ApplicationCommands.New}" Header="New row"/>
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
<Button x:Name="Create"
Content="Create"
Click="Create_Click" Foreground="White" FontWeight="Bold" Width="100" Height="25" Background="#5cb85c" RenderTransformOrigin="0.67,0.219" />
Code Behind:代码背后:
public partial class BulkGroupCreationUserControl : UserControl
{
BulkGroupCreationClass bulkGroupCreationObj = new BulkGroupCreationClass();
private ObservableCollection<BulkGroupCreationModel> _bulkGroupCreationCollection;
public ObservableCollection<BulkGroupCreationModel> BulkGroupCreationCollection
{
get { return _bulkGroupCreationCollection ?? (_bulkGroupCreationCollection = new ObservableCollection<BulkGroupCreationModel>()); }
set { _bulkGroupCreationCollection = value; }
}
//constructor
public BulkGroupCreationUserControl()
{
InitializeComponent();
bulkGroupCreationDataGrid.ItemsSource = BulkGroupCreationCollection;
}
buttonClick Code按钮点击代码
private async void Create_Click(object sender, System.Windows.RoutedEventArgs e)
{
//Just checking whether i receive data here, I receive it when data manually typed in grid, but not when uploaded from excel
BulkGroupCreationCollection.Count;
}
Excel to data grid data upload Excel到数据网格数据上传
private void Upload_Click(object sender, RoutedEventArgs e)
{
//Paste here
OpenFileDialog openfile = new OpenFileDialog();
openfile.DefaultExt = ".xlsx";
openfile.Filter = "(.xlsx)|*.xlsx";
//openfile.ShowDialog();
var browsefile = openfile.ShowDialog();
if (browsefile == true)
{
txtFileUpload.Text = openfile.FileName;
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
//Static File From Base Path...........
//Microsoft.Office.Interop.Excel.Workbook excelBook = excelApp.Workbooks.Open(AppDomain.CurrentDomain.BaseDirectory + "TestExcel.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
//Dynamic File Using Uploader...........
Microsoft.Office.Interop.Excel.Workbook excelBook = excelApp.Workbooks.Open(txtFileUpload.Text.ToString(), 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Microsoft.Office.Interop.Excel.Worksheet excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelBook.Worksheets.get_Item(1); ;
Microsoft.Office.Interop.Excel.Range excelRange = excelSheet.UsedRange;
string strCellData = "";
double douCellData;
int rowCnt = 0;
int colCnt = 0;
System.Data.DataTable dt = new System.Data.DataTable();
for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)
{
string strColumn = "";
strColumn = (string)(excelRange.Cells[1, colCnt] as Microsoft.Office.Interop.Excel.Range).Value2;
dt.Columns.Add(strColumn, typeof(string));
}
for (rowCnt = 2; rowCnt <= excelRange.Rows.Count; rowCnt++)
{
string strData = "";
for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)
{
try
{
strCellData = (string)(excelRange.Cells[rowCnt, colCnt] as Microsoft.Office.Interop.Excel.Range).Value2;
strData += strCellData + "|";
}
catch (Exception ex)
{
douCellData = (excelRange.Cells[rowCnt, colCnt] as Microsoft.Office.Interop.Excel.Range).Value2;
strData += douCellData.ToString() + "|";
}
}
strData = strData.Remove(strData.Length - 1, 1);
dt.Rows.Add(strData.Split('|'));
}
bulkGroupCreationDataGrid.ItemsSource = dt.DefaultView;
excelBook.Close(true, null, null);
excelApp.Quit();
}
}
}
Look at this line in your Upload_Click method:在Upload_Click方法中查看这一行:
bulkGroupCreationDataGrid.ItemsSource = dt.DefaultView;
What are you doing here?你在这里做什么? You are setting the DataGrid's ItemsSource to dt.DefaultView .您将 DataGrid 的 ItemsSource 设置为dt.DefaultView 。 In other words, when this line is being executed the DataGrid's ItemsSource is not the ObservableCollection anymore, it's dt.DefaultView .换句话说,当执行此行时,DataGrid 的 ItemsSource 不再是 ObservableCollection,而是dt.DefaultView 。 Additionally, the Upload_Click method reads the data from the Excel sheet into the DataTable, not into the ObservableCollection.此外, Upload_Click方法将 Excel 工作表中的数据读入 DataTable,而不是 ObservableCollection。 (As a side note, even if your were to set your ItemsSource binding to be in TwoWay mode in an attempt to pass the new ItemsSource value back to the bound (View)Model property, it would quite likely not work without some changes in the respective (View)Model and possibly elsewhere in your code because a DataTable.DefaultView is not convertible to an ObservableCollection.) (作为旁注,即使您将 ItemsSource 绑定设置为 TwoWay 模式以尝试将新的 ItemsSource 值传递回绑定的 (View)Model 属性,如果不对相应的 (View)Model 并且可能在代码中的其他位置,因为 DataTable.DefaultView 不能转换为 ObservableCollection。)
Consequently, when Upload_Click is executed, the ObservableCollection provided by the (View)Model used as DataContext remains untouched (because of the Excel data not going into the ObservableCollection, and the DataGrid not using the ObservableCollection as its ItemsSource anymore).因此,在执行Upload_Click时,用作 DataContext 的 (View)Model 提供的 ObservableCollection 保持不变(因为 Excel 数据不会进入 ObservableCollection,并且 DataGrid不再使用 ObservableCollection 作为其 ItemsSource)。
Instead of swapping the ItemsSource of the DataGrid, i suggest you choose either DataTable or ObservableCollection as the type of your DataGrid's ItemsSource and stick with it.与其交换 DataGrid 的 ItemsSource,我建议您选择 DataTable或ObservableCollection 作为 DataGrid 的 ItemsSource 的类型并坚持下去。 Do not manipulate the DataGrid's ItemsSource property directly.不要直接操作 DataGrid 的 ItemsSource 属性。 If you need to load (or change) content of the DataGrid programmatically (for example as part of the Upload_Click method), alter the DataTable / ObservableCollection instance that is already bound to the DataGrid and is part of the (View)Model that serves as the DataContext for the DataGrid's ItemsSource binding.如果您需要以编程方式加载(或更改)DataGrid 的内容(例如作为Upload_Click方法的一部分),请更改已绑定到 DataGrid 并且是用作 (View)Model 的一部分的 DataTable / ObservableCollection 实例DataGrid 的 ItemsSource 绑定的 DataContext。
If you really need to change the bound DataTable/ObservableCollection to a different DataTable/ObservableCollection instance, change the value of the BulkGroupCreationModel property in the respective (View)Model that serves as DataContext, instead of manipulating the DataGrid's ItemsSource directly in the code-behind.如果您确实需要将绑定的 DataTable/ObservableCollection 更改为不同的 DataTable/ObservableCollection 实例,请更改用作 DataContext 的相应 (View)Model 中BulkGroupCreationModel属性的值,而不是直接在代码隐藏中操作 DataGrid 的 ItemsSource .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.