【发布时间】:2016-04-04 20:19:20
【问题描述】:
我的目标是在 WPF 中拥有一组级联组合框。我正在尝试使用 MVVM 模型,但仍在学习。
项目的一些背景信息。我正在尝试为员工编辑时间。
所以我有一个 DataGrid 中选定员工的时间列表。 DataGrid 中的每一行都是一个 Time 对象。时间由一些字段 InTime、OutTime、Date、Hours... 等组成。一个时间也有一个部门和一个工作。
目前我的部门组合框已连接并正常工作,但我不确定如何根据部门字段中选择的内容构建工作组合框。
这是我的 ViewModel 的设置方式
public ObservableCollection<Time> Times { get; set; }
public ObservableCollection<Department> Departments { get; set; }
public TimeSheetsViewModel()
{
Times = new ObservableCollection<Time>();
Departments = new ObservableCollection<Departments>();
GetDepartments();
}
private void GetDepartments()
{
/*
This section contains code to connect to my SQL Database and fills a DataTable dt
*/
if (Departments != null)
Departments.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
Department d = new Department() { Display = dt.Rows[i]["DISPLAY"].ToString(), DepartmentCode = dt.Rows[i]["DEPARTMENT_CODE"].ToString(), CompanyCode = dt.Rows[i]["COMPANY_CODE"].ToString() };
Departments.Add(d);
}
}
这是我的 DataGrid 上的绑定
<DataGrid Grid.Row="1" Margin="15,0,15,15" Visibility="Visible" FontSize="14" HorizontalGridLinesBrush="{StaticResource Nelson2}" VerticalGridLinesBrush="{StaticResource Nelson2}" ItemsSource="{Binding Times}" SelectionMode="Single" CellEditEnding="DataGrid_CellEditEnding" RowEditEnding="DataGrid_RowEditEnding" AutoGenerateColumns="False">
<DataGridTemplateColumn Header="Department Code">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path= Department.Display}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource Findancestor, AncestorType={x:Type UserControl}}, Path=DataContext.Departments}" DisplayMemberPath="Display" SelectedValuePath="DepartmentCode" SelectedValue="{Binding Department.DepartmentCode}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid>
那么我如何实现我的工作组合框以根据为该行中的部门选择的任何内容填充其项目?
我假设我想将代码放在我的同一个视图模型中。
感谢任何帮助,谢谢!
编辑(04/05/16):
如何返回一个带有转换器的对象,以便我可以使用该转换器将不同的东西绑定到该对象的字段。
说这是我的转换器
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
string departmentCode = values[0].ToString();
ObservableCollection<Department> Departments = values[1] as ObservableCollection<Department>;
return Departments.FirstOrDefault(Department => Department.DepartmentCode == departmentCode);
}
这是我的绑定
<TextBlock >
<TextBlock.Text>
<MultiBinding Converter="{StaticResource DeptCodeToDeptConverter}" >
<Binding Path="DepartmentCode" />
<Binding Path="DataContext.Departments" RelativeSource="{RelativeSource Findancestor, AncestorType={x:Type UserControl}}"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
该转换器将返回一个部门对象,但如果我希望 TextBlock 的文本为 Department.Name 或 Department.Location 怎么办。我是否必须创建一个新的转换器来返回我想在不同控件中使用的每个字段?或者有没有办法使用这种方法来实现我想要的?
【问题讨论】:
标签: c# wpf mvvm datagrid cascadingdropdown