【发布时间】:2015-01-06 11:09:39
【问题描述】:
我是 WPF 新手,谁能解释我如何在 MVVM 模型中使用 WPF 选择 DataGrid 表格行并通过单击按钮将其删除。
我只能通过硬编码值来通过按钮单击删除行。
HostSystemInformation info = (from sysinfo in systemInformation
where sysinfo.Sno == 4
select sysinfo).First();
从上面的代码我只能删除第 4 行。当我在数据网格表中选择一行时,我想要在变量中获取值的解决方案。我想使用该变量而不是硬编码值 4。 此编码不是在代码隐藏中完成的,而是在单独的 ModalView 文件中完成的
我已经复制了我的代码,下面有人对此给出了解决方案。
XAML:
<Button Content="Remove" Command="{Binding DeleteIp}" Grid.Row="0" Grid.Column="1" FontFamily="Ebrima" FontSize="12" Width="61" Height="25" HorizontalAlignment="right" VerticalAlignment="center"/>
<DataGrid Name="datagridIpTable" ItemsSource="{Binding SystemInformation}" SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}" AutoGenerateColumns="false" Grid.Row="1" Grid.Column="1" CanUserAddRows="False" >
<DataGrid.Columns >
<DataGridTextColumn Binding="{Binding Sno}" Header="S.No" MinWidth="50" />
<DataGridTextColumn Binding="{Binding strIpAddr}" Header="System Name" MinWidth="240"/>
<DataGridTextColumn Binding="{Binding strSystemName}" Header="IP Address" MinWidth="240"/>
<DataGridTextColumn Binding="{Binding strStatus}" Header="Status" MinWidth="140" />
</DataGrid.Columns>
</DataGrid>
ModalView.cs文件
private DelegateCommand deleteIp;
public DelegateCommand DeleteIp
{
get { return deleteIp; }
set { deleteIp = value; }
}
private ObservableCollection<HostSystemInformation> systemInformation;
public ObservableCollection<HostSystemInformation> SystemInformation
{
get { return systemInformation; }
set { SetProperty(ref systemInformation, value); }
}
public UserBase_ViewModal()
{
SystemInformation = new ObservableCollection<HostSystemInformation>();
deleteIp = new DelegateCommand(DeleteSystemInformationInIpTable);
}
private void DeleteSystemInformationInIpTable()
{
try
{
if(systemInformation.Count>0)
{
int count=0;
foreach (object eno in systemInformation)
{
HostSystemInformation info = (from sysinfo in systemInformation
where sysinfo.Sno == 4
select sysinfo).First(); /*Here instead of 4th row i need to pass variable dynamically by pressing any row */
systemInformation.Remove(info);
count++;
}
}
}
catch (Exception ex)
{
// MessageBox.Show(ex.Message);
}
}
public class HostSystemInformation
{
public int Sno { get; set; }
public string strIpAddr { get; set; }
public string strSystemName { get; set; }
public string strStatus { get; set; }
}
【问题讨论】: