我需要从datagrid获取数据并独立于datagrid处理这些数据。
我在XAML中写道:
<Window x:Class="DatagridExample1.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:DatagridExample1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Height="26" Margin="10,0,0,0" VerticalAlignment="Top" Width="774" Click="button_Click"/>
<DataGrid x:Name="dg" HorizontalAlignment="Left" Height="379" Margin="10,31,0,0" VerticalAlignment="Top" Width="774" SelectionChanged="dg_SelectionChanged" AutoGenerateColumns="False" SelectionUnit="CellOrRowHeader" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Reference" Binding="{Binding Reference}" IsReadOnly="True"/>
<DataGridTextColumn Header="Value" Binding="{Binding Value}" Width="*"/>
<DataGridTextColumn Header="PartName" Binding="{Binding PartName}" Width="*"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
书面类别部分如下:
public class Part
{
public Part()
{
}
public string Reference { get; set; }
public string Value { get; set; }
public string PartName { get; set; }
}
和
之后,我用Part的对象编写了一个集合,填充这些集合并将其推送到datagrid中。
public List<Part> list;
public MainWindow()
{
Part p1 = new Part() { Reference = "R1", Value = "10R", PartName = "10R 0402" };
Part p2 = new Part() { Reference = "R2", Value = "10R", PartName = "10R 0402" };
Part p3 = new Part() { Reference = "R3", Value = "10R", PartName = "10R 0402" };
list = new List<Part>(){};
list.Add(p1);
list.Add(p2);
list.Add(p3);
list.Add(p1);
InitializeComponent();
dg.ItemsSource = list;
}
这部分还可以。运行程序后,我可以看到我的表:(见链接中的图像)Main window: correct table
之后,我点击了按钮并运行以下代码:
private void button_Click(object sender, RoutedEventArgs e)
{
List<Part> oldList = (dg.ItemsSource as List<Part>);
Part[] p = oldList.ToArray();
p[0].Reference += p[1].Reference;
}
看起来好吧。我只使用数组“p”,我没有使用“dg”但是当我在表中对列进行排序时。我真的很困惑,因为“dg”中的数据是变化的。怎么样,为什么?我怎样才能解决这个问题。因为我需要在datagrid上独立使用数组。
嗯,这是因为你正在改变对象本身。
你创建一个新的List
并不重要,因为它是内存中相同引用的列表。更改任何值后,它将反映在显示这些对象的网格中。
如果您想要“播放”这些对象而没有反映网格的那些对象,则需要新对象。您需要将它们复制到不同的引用。