[英]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-Name
从grid
删除一行,预先感谢!
AddToGrid
class to MyGridRow
and move it to be a public type instead of a nested type. AddToGrid
类重命名为MyGridRow
并将其移动为公用类型而不是嵌套类型。 using System.Linq;
using System.Linq;
添加using System.Linq;
and using System.Collections.ObjectModel;
using System.Collections.ObjectModel;
to your C# code-behind file. In your XAML code-behind, add this public property: 在您的XAML后台代码中,添加以下公共属性:
public ObservableCollection<MyGridRow> MyGridRows { get; } = new ObservableCollection<MyGridRow>();
Change your XAML to this: 将您的XAML更改为此:
<DataGrid ItemsSource="{Binding MyGridRows}" ...> </DataGrid>
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 } );
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.