How to reuse XAML code

0

Hi, I'm doing an application in WPF which consists of several pages. Many of which have things in common, such as the same menu bar, a title bar below the menu bar and a scrool viewer which contains all the other controls that differentiates one page from another.

What I have done so far is Create a page with the menu bar and a frame in which I show the other pages, that is, the information different from the other pages.

I would like to know what is the best way to do these things and not to repeat code. Greetings and excuse my modest knowledge.

    
asked by Sauli 08.06.2017 в 21:04
source

1 answer

2

I do that by creating UserControls, and I save them in the Views folder, eye, you can carry a ViewModel binding as well as you can not take it, it's your design.

<UserControl x:Class="MyProject.Views.FantasticMenu"
            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"     
            xmlns:vm="clr-namespace:MyProject.ViewModels"
            mc:Ignorable="d" 
           d:DesignHeight="32" d:DesignWidth="600">
    <UserControl.Resources>
        <vm:MyOptionalMenuViewModel x:Key="MyViewModel"/>
    </UserControl.Resources>
    <Grid DataContext="{StaticResource MyViewModel}">
        <!-- diseño del control -->
    </Grid>
</UserControl>

Then on the page where you want to use it, add the namespace:

xmlns:view="clr-namespace:MyProject.Views"

and later I add the control I did inside a Grid or another container ..

<Grid>
 <view:FantasticMenu/>
</Grid>

That's it, just keep in mind that every time you put it in XAML you'll be creating a new instance of the control, it will not be the same.

EDIT:

To complement the answer:

In the last example XAML leave it like this:

<Grid>
        <view:FantasticMenu x:Name="myMenu"/>
</Grid>

In the XAML of userControl you add the grid you mention:

<Grid x:Name="grid_controls" Margin="0"/>

Then in the C # code of the UserControl, make a method like this:

public void AgregarControl(UIElement control)
{
    grid_controls.Children.Add(control);
}

and when you want to add something to the grid that is in the UserControl you can do it from where you have access to it in this way, for example, adding a datepicker to the grid that is inside the usercontrol ..

private void AgregarControlAlUserControl()
{
    DatePicker dp = new DatePicker();
    myMenu.AgregarControl(dp);
}

That makes it clearer, I suppose.

    
answered by 09.06.2017 в 01:00