My XAML has got very long and hard to maintain. I was wondering if there is a way to do something like refactoring?
Here is a simple example:
<Window x:Class="RefactorXAML.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel>
<Button>New</Button>
<Button>Open</Button>
</StackPanel>
</Grid>
</Window>
How can I refactor the Stackpanel
section and write something like this?
<Window x:Class="RefactorXAML.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
// Refactored Markup
</Grid>
</Window>
You could put those buttons in a user control, to make it like this:
<Window …
xmlns:my="clr-namespace:SomeNamespace">
<Grid>
<my:NewAndOpenButtons />
</Grid>
</Window>
You could also replace the grid by an items control which already includes those buttons, but that way you would impose too many restrictions on the other content, so I wouldn’t do that.
So for the above, your user control would look something like this:
<UserControl x:Class="SomeNamespace.NewAndOpenButtons" …>
<StackPanel>
<Button>New</Button>
<Button>Open</Button>
</StackPanel>
</UserControl>
1) using content control
<Window.Resources>
<ControlTemplate x:Key="Stackpanel" TargetType="ContentControl">
<StackPanel>
<Button>New</Button>
<Button>Open</Button>
</StackPanel>
</ControlTemplate>
</Window.Resources>
<Grid>
<ContentControl Template="{StaticResource Stackpanel}"></ContentControl>
</Grid>
2)create new usercontrol
<UserControl x:Class="WpfApplication2.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<StackPanel>
<Button>New</Button>
<Button>Open</Button>
</StackPanel>
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:local="clr-namespace:WpfApplication2">
<Grid>
<local:UserControl1></local:UserControl1>
</Grid>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With