如何根据数据网格的选定项设置多个元素的datacontext?

时间:2012-01-02 21:11:13

标签: c# wpf binding mvvm

在我需要的时候,我再次问你stackoverflow。

我正在尝试将工具栏,菜单和DataGrid(datagrid_worksessions)绑定到另一个DataGrid(datagrid_employees)的选定项目。棘手的部分是我需要工具栏和菜单绑定到元素ViewModel层,而DataGrid绑定到该特定对象的模型层。

这是我的ViewLayer的代码隐藏。如果您需要更多信息,请与我们联系。

namespace SalaryApplication
{
public partial class MainWindow : Window
{
    public EmployeeViewModel EmployeeViewModel = new EmployeeViewModel();

    private ObservableCollection<WorkSessionModel> SelectedWorkSessions = new ObservableCollection<WorkSessionModel>();


    public MainWindow()
    {
        InitializeComponent();

        menu_employee.DataContext = EmployeeViewModel;
        sp_employee.DataContext = EmployeeViewModel;
        datagrid_employees.ItemsSource = EmployeeViewModel.EmployeesView;

        sp_worksessions.DataContext = EmployeeViewModel.WorkSessionViewModel;
        menu_worksession.DataContext = EmployeeViewModel.WorkSessionViewModel;



    }

    private void datagrid_employees_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
        grid_selectedEmployee.DataContext = EmployeeViewModel.SelectedEmployee;
        SelectedWorkSessions = EmployeeViewModel.SelectedEmployee.WorkSessions;
        datagrid_worksessions.ItemsSource = SelectedWorkSessions;
    }
}
}

2 个答案:

答案 0 :(得分:1)

DataContext是一个可继承的Dependency属性,这意味着如果您为父GUI设置它,那么所有子元素将自动获取它。

因此,在您的情况下,只需设置窗口\用户控件的数据上下文即可生成menu_employeesp_employeedatagrid_employeessp_worksessionsmenu_worksessiongrid_selectedEmployee(假设他们不是任何ItemsControl的一部分)自动获取它。

获取数据上下文后,只需使用BindingPath从数据上下文映射到相关对象。

下面的例子会给你一个想法......(仅用于说明目的)

   <Window ... >
       <Menu ItemsSource="{Binding MenuItems}" ... />
       <StackPanel>
            <DataGrid ItemsSource="{Binding Employees}"/>
            <DockPanel DataContext="{Binding SelectedEmployee}">
                <TextBlock Text="{Binding Name}"/>
            </DockPanel>
       </StackPanel>
   </Window> 

代码背后

    public MainWindow()
    {
        InitializeComponent();
        //// Now every item in your `Window` hierarchy above autotmatically gets 
        //// the data context as the instance of EmployeeViewModel class.
        this.DataContext = new EmployeeViewModel(); 
    }  

以下是视图模型和模型的伪对象层次结构......

  EmployeeViewModel Class
    -> Property List<MenuItem> MenuItems
    -> Property List<Employee> Employees
    -> Property Employee SelectedEmployee

  Employee Class
    -> Property String Name 

答案 1 :(得分:0)

为什么不能在xaml中设置datacontext?

<DataGrid Name="grid_selectedEmployee" DataContext="{Binding EmployeeViewModel.SelectedEmployee}">

<DataGrid Name="datagrid_worksessions" ItemSource="{Binding SelectedWorkSessions}" >

只需确保SelectedEployee是DependancyProperty或EmployeeViewModel实现INotifyProperty已更改。