简体   繁体   English

WPF根据单元格值删除datagrid行

[英]WPF delete datagrid row based on cell value

I am facing a problem right now, I need to delete a datagrid row based on 1 cell value, code samples below: 我现在面临一个问题,我需要基于1个单元格值删除一个datagrid行,以下代码示例:

XAML: XAML:

<DataGrid
    x:Name="AccountGrid"
    IsSynchronizedWithCurrentItem="True"
    GridLinesVisibility="Vertical" 
    ItemsSource="{Binding}"
    CanUserAddRows="False"
    CanUserReorderColumns="False"
    CanUserResizeColumns="False"
    CanUserSortColumns="False" 
    AutoGenerateColumns="False"
    CanUserResizeRows="False" 
    HorizontalContentAlignment="Left"
    ScrollViewer.HorizontalScrollBarVisibility="Disabled" 
    Margin="208,0,0,135"
>
   <DataGrid.Columns>
       <DataGridTextColumn Header="VM-Name" Binding="{Binding Path=vmName}" MinWidth="80" IsReadOnly="True" />
       <DataGridTextColumn Header="Profile" Binding="{Binding Path=profileN}" MinWidth="100" IsReadOnly="True" />
   </DataGrid.Columns>
</DataGrid>

How I add items: 我如何添加项目:

public class AddToGrid
{
   public string vmName   { get; set; }
   public string profileN { get; set; }
}

this.Dispatcher.Invoke(() =>
{
   var dat = new AddToGrid { vmName = clientSockets.Find(item => item.Item1 == current).Item2, profileN = profile.Item1 };
   AccountGrid.Items.Add( dat );
});

What I need to do is Delete a row from the grid , using the VM-Name , Thanks in advance! 我需要做的是使用VM-Namegrid 删除一行,预先感谢!

  1. Rename your AddToGrid class to MyGridRow and move it to be a public type instead of a nested type. 将您的AddToGrid类重命名为MyGridRow并将其移动为公用类型而不是嵌套类型。
  2. Add using System.Linq; using System.Linq;添加using System.Linq; and using System.Collections.ObjectModel; using System.Collections.ObjectModel; to your C# code-behind file. 到您的C#代码隐藏文件。
  3. In your XAML code-behind, add this public property: 在您的XAML后台代码中,添加以下公共属性:

     public ObservableCollection<MyGridRow> MyGridRows { get; } = new ObservableCollection<MyGridRow>(); 
  4. Change your XAML to this: 将您的XAML更改为此:

     <DataGrid ItemsSource="{Binding MyGridRows}" ...> </DataGrid> 
  5. Change your code that adds items to this: 更改添加代码的代码:

     String vmName = clientSockets.Find( item => item.Item1 == current ).Item2; String profile = profileN = profile.Item1; this.MyGridRows.Add( new MyGridRow { VMName = vmName, ProfileN = profile } ); 
  6. To remove a row, do this: 要删除行,请执行以下操作:

     MyGridRow itemToRemove = this.MyGridRows .FirstOrDefault( pair => pair.Item.VMName == "someName" ) if( itemToRemove != null ) { this.MyGridRows.Remove( itemToRemove ); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM