我的视图模型中有以下属性:
public List<Departments> DepartmentList
{
get { return NewTechnician.departmentList; }
set
{
NewTechnician.departmentList = value;
OnPropertyChanged("DepartmentList");
}
}
我有一个绑定到此列表的DataGrid,其值为
public class Departments
{
public int departmentId { get; set; }
public string departmentDescription { get; set; }
public int requestAccess { get; set; }
public int queueAccess { get; set; }
public int departmentStatus { get; set; }
public bool selected { get; set; }
}
我需要能够将所选行中的departmentid插入到我的数据库中。如何根据现有列表或新列表中的选定行绑定departmentID的值。 (选择模式设置为扩展)
foreach (Departments department in createNewTech.selectedDepartments)
{
if (department.selected == true)
{
sql = @"insert into Tech_Department_Link Values(@techId,@DepartmentId)";
using (SqlCommand command = new SqlCommand(sql, con))
{
command.Parameters.AddWithValue("@TechID", createNewTech.newTech.techID);
command.Parameters.AddWithValue("@DepartmentId", department.departmentId);
command.ExecuteNonQuery();
}
}
}
答案 0 :(得分:0)
首先,最好不要将PlainIigs中的ModelItems插入到Datagrid中。最好你应该使用DepartmentViewModel的Generic Type创建一个ObservableCollection,它包含部门和属性,就像你的&#34; IsSelected&#34;,它不是一个真正的模型属性,而是你的逻辑和帮助属性图。
然后你可以进入你的Datagrid所在的Xaml,并执行以下操作:
<DataGrid ItemsSource="{Binding DepartmentViewModels}">
<DataGrid.ItemContainerStyle>
<Style TargetType="DataGridRow">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
</Style>
</DataGrid.ItemContainerStyle>
</DataGrid>
所有部门的Viewmodel都拥有如下属性:
public ObservableCollection<DepartmentViewModel> DepartmentViewModels
然后你可以通过
获得所选部门的所有IDvar ids = (from dpvm in this.DepartmentViewModels
where dpvm.IsSelected
select dpvm.Id).ToList();
修改强> 如果您想直接在列表中使用模型,则第一个剪切必须如下:
<DataGrid ItemsSource="{Binding DepartmentList}">
<DataGrid.ItemContainerStyle>
<Style TargetType="DataGridRow">
<Setter Property="IsSelected" Value="{Binding selected, Mode=TwoWay}" />
</Style>
</DataGrid.ItemContainerStyle>
</DataGrid>