I have a WPF application that uses a TabControl. Each TabItem will contain a datagrid. When the application starts up, there is one TabItem that loads by default that displays an "Accounts" datagrid. This datagrid displays only account information. The user can then choose to add new Tabs. For each tab that is added, I need the same datagrid to be loaded. It is NOT the same datagrid that is used for the Accounts TabItem. The new datagrid will be used to enter transactions. How can I define a datagrid that I can use in each newly added TabItem, but is different than the original datagrid on the first TabItem?
So if I understand correctly what you want is a default DataGrid
for the first tabitem
and then for each new tabitem
same datagrid
.
Problem here is that a single DataGrid
cannot be part of Two TabItems
at the same time. So what you would have to do it first declare a DataGrid
in a scope where it can be accessed in the code behind. Next, when user adds a new tabitem
, first time, add a tab item
dynamically in the tab control
and set content
equal to DataGrid
. When user clicks the add new tab item again, remove the content
of tab item which previously had DataGrid
and then Add datagrid
in the new tab item
. You will also have to handle the selection change
event of tabs and inside that event you will have to remove DataGrid
from last selected item and put in the newly selected item.
I am not sure you really need this same dataGrid for different tab items thing or not but think before implementing this approach about other possible solutions
In this case, I'd recommend using the MVVM pattern.
Have your main ViewModel define an public ObservableCollection<object> Items
property. Bind your TabControl
's ItemsSource
to the Items
.
Define a DataTemplate
for an AccountsViewModel
which contains the DataGrid
which should be displayed on the Accounts TabItem
.
Define a DataTemplate
for a TransactionsViewModel
which contains the DataGrid
which should be displayed on each Transactions TabItem
.
On the Account Tab
add in XAML
a DataGrid
, let's say AccountDataGrid
For other types, as they generated at runtime, it's better to manage them from the code.
Create DataGrid
object that will be shared by other TabItems
, let's say SharedDataGrid
After you can do something like this, for example:
Define your custom TabItem
class
public sealed class CustomTabItem : TabItem
{
}
and after override inside that class
protected override void OnInitialized(EventArgs e)
{
//assign shared SharedDataGrid to the content of TabItem
}
In that method actually assign SharedDataGrid to the content of the just created and initialized TabItem
.
Should work.
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.