简体   繁体   中英

Setting DataContext in TabControl

I have a TabControl that is bound to an observable collection of Employees like so

<TabControl ItemsSource="{Binding Employees}">
            <TabControl.ContentTemplate>
                <DataTemplate>
                    <views:EmployeeView/>
                </DataTemplate>
            </TabControl.ContentTemplate>
        </TabControl>

I have set my DataTemplate to my employee view. Say I have two employees in my Employees collection. I get the proper tabs to appear. In my EmployeeView I have a checkbox. If I do not bind this checkbox it gets checked on all tabs. I'm not sure I am following why this is happening. I guess my question is how would I set the DataContext on the EmployeeView so that that the tabcontrols tabs would operate independently.

The problem could be that when the TabControl is databound it 'virtualises' its TabItems, unloading then reloading and rebinding their content when selection changes.

So you could try either binding the IsChecked of the CheckBox in your View to a property of its ViewModel , or disable the TabItem virtualisation with a behaviour such as the one here: http://www.codeproject.com/Articles/460989/WPF-TabControl-Turning-Off-Tab-Virtualization

I used the above behaviour recently myself as I had a similar issue with TabControl's default databound behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM