Having trouble removing duplicated code in XAML code.
Example:
<TabControl x:Name="TabControl">
<TabItem Header="1">
<TabItem.Content>
<GridView x:Name="GridView1">
...
</GridView>
</TabItem.Content>
</TabItem>
<TabItem Header="2">
<TabItem.Content>
<GridView x:Name="GridView2">
...
</GridView>
</TabItem.Content>
</TabItem>
</TabControl>
Contents of tabs are identical, except for the names of the GridView controls.
I need tabs to be statically created through XAML, in order to access the GridView's in code-behind.
Is there a way to keep the content of TabItems in one place, so it could be used for both TabItems, but to preserve the possibility to access both GridView's separately in code-behind?
CodePudding user response:
If you are referring to the entire GridView content, you can create your own control just as you would a form. But instead of
<Window x:Class...
other xmlns stuff of window >
[actual content within]
</Window>
Just create a file with the content of your gridview such as
<GridView x:Class="classNameOfThisControl"
other xmlsns stuff like that of Window >
[content within the gridview]
</GridView>
Then, in your tab control that is duplicated, you could add this custom xaml content
<TabControl x:Name="TabControl">
<TabItem Header="1">
<TabItem.Content>
<local:classNameOfThisControl x:Name="GridView1"/>
</TabItem.Content>
</TabItem>
<TabItem Header="2">
<TabItem.Content>
<local:classNameOfThisControl x:Name="GridView2"/>
</TabItem.Content>
</TabItem>
</TabControl>
The context of "local" as you would see in your existing is basically context to your own project and the class name created in the previous step. I have done this way for many things that can get re-used in multiple places. Imagine an app that needs name and addresses. Why recreate 20 times. Declare the same context of grid, column alignments, text entry, etc and just have whatever binding context assigned at that one level and the inner pieces (provided same binding property names context) and it works smoothly. HTH
Feedback
If your more complete [GridView] and each instance has multiple controls and you want to know the controls within that explicitly, you can still use the x:Name context of the parts, but you would first need to get the first instance gridview name, then FIND the parts of the other controls within it. Because GridView1.SomeTextbox would be an obviously different object than GridView1.SomeTextbox in ITs presentation. Make sense? If you can EDIT your existing post and maybe provide a little more context of what you are trying to do MIGHT help add clarification.
Another way might be to make your own custom class with certain properties and have the context of those bound to a pre-defined TEMPLATE/STYLE that knows of your custom class and its related Bindable Properties, but that gets into a bit more than where you are at the moment.