我最近从WinForms转移到了WPF,看起来像datagrids处理在这里更复杂。我必须在应用程序运行时从用户界面手动在数据网格中添加数据。
我有以下XAML代码:
<DataGrid x:Name="dataGridAdd" HorizontalAlignment="Left" Margin="591,360,0,0" VerticalAlignment="Top" Height="118" Width="202" AutoGenerateColumns="False" ScrollViewer.CanContentScroll="False" VerticalScrollBarVisibility="Disabled" Grid.Column="1" CanUserDeleteRows="True">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Varenr}" ClipboardContentBinding="{x:Null}" Header="Vare nr.:" Width="100"/>
<DataGridTextColumn Binding="{Binding Antal}" ClipboardContentBinding="{x:Null}" Header="Antal" Width="100"/>
</DataGrid.Columns>
</DataGrid>
后台代码:
public partial class Window1 : Window
{
ObservableCollection<Add> list;
public Window1()
{
InitializeComponent();
list = new ObservableCollection<Add>();
dataGridAdd.ItemsSource = list;
}
public class Add
{
public string Varenr { get; set; }
public string Antal { get; set; }
}
private void buttonPrint_Click(object sender, RoutedEventArgs e)
{
Add addval = dataGridAdd.SelectedItem as Add;
while (dataGridAdd.Items.Count > 1)
{
string vare = addval.Varenr;
string antal1 = addval.Antal;
list.Remove(addval);
}
}
}
关键是,当我使用单行添加数据并按下打印按钮时,它会按预期删除项目:
当我添加多行时会出现问题:
while循环变为无限,因为在这种情况下dataGridAdd.Items.Count不会低于值“2”。我该如何处理这个问题?
答案 0 :(得分:0)
这是一个错误的逻辑。例如,如果您在dataGridAdd中有超过2个项目,那么您的代码将被执行如下:
Add addval = dataGridAdd.SelectedItem as Add;
while (dataGridAdd.Items.Count > 1)
{
string vare = addval.Varenr;
string antal1 = addval.Antal;
list.Remove(addval);
}
所以,dataGridAdd.Items.Count不会低于值“2”
顺便说一句,为什么在这种情况下使用呢?<强>更新强>
运行此代码,您将在list.Remove(addval)之后看到dataGridAdd.SelectedIndex = -1
和dataGridAdd.SelectedItem = null
;所以,如果再次移除,它将返回flase。
private void Button_Click(object sender, RoutedEventArgs e)
{
Add addval = dataGridAdd.SelectedItem as Add;
Console.WriteLine(dataGridAdd.SelectedIndex);
Console.WriteLine(dataGridAdd.SelectedItem);
string vare = addval.Varenr;
string antal1 = addval.Antal;
list.Remove(addval);
Console.WriteLine(dataGridAdd.SelectedIndex);
Console.WriteLine(dataGridAdd.SelectedItem);
}
答案 1 :(得分:0)
使用wpf / mvvm时,不要删除或添加数据网格中的项目!您删除并添加项目到基础数据源。
public ObservableCollection<MyDataTypeObjects> MyData {get;set;}
public MyDataTypeObjects MySelectedData {get;set;}
XAML
<DataGrid ItemsSource="{Binding MyData}" SelectedItem="{Binding MySelectedData}"/>
答案 2 :(得分:0)
现在可以使用以下代码:
private void buttonPrint_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < dataGridAdd.Items.Count - 1; i++)
{
Add addval = dataGridAdd.Items[i] as Add;
string vare = addval.Varenr;
string antal1 = addval.Antal;
}
list.Clear();
}