eeadev
eeadev

Reputation: 3852

Add XAML programmatically in Windows Phone

I need to add programmatically some UI.

In order to do that I am creating each single Object and adding it to my main grid.

This way (I need to do that in a lambda function):

        Deployment.Current.Dispatcher.BeginInvoke(() => {
            StackPanel stkpanel = new StackPanel();
            stkpanel.Orientation = Orientation.Horizontal;
             TextBlock textBlock = new TextBlock();
            textBlock.Text = "text1";
            Grid myGrid = new Grid();
            myGrid.Children.Add(textBlock);

            MainPage currentPage = (MainPage)(((App)Application.Current).RootFrame.Content as PhoneApplicationPage);
            currentPage.LayoutRoot.Children.Add(myGrid);
 ...
});

Is there a way to add to my MainPage.xaml another File.xaml and display the result?

I am using silverlight 8.1

Thanks

Upvotes: 2

Views: 470

Answers (1)

Koopakiller
Koopakiller

Reputation: 2884

There some different ways to do that.

UserControl

One way is to create a user Control and use it direct in XAML or instantiate it in the code behind like a standard control. You can find a template in the Add Item dialog in Visual Studio.

Pages

It is also possible to create a second page and Display them in a Frame tag. It is possible in XAML and code behind. Here is an example:

<Frame Margin="0,148,0,0" Name="myFrame"/>

myFrame.Navigate(typeof(BlankPage1));

XamlReader

If you have a partial XAML code, stored in a file you can parse it manual and add the objects to the page. Your XAML must look like the following with the xmlns Attribut

<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Button Content="BTN 1" />
    <Button Content="BTN 2" />
    <Button Content="BTN 3" />
</StackPanel>

Then you can parse it with XamlReader:

var uri = new Uri("ms-appx:///test.xaml");
var file = await StorageFile.GetFileFromApplicationUriAsync(uri);

var panel = XamlReader.Load(await FileIO.ReadTextAsync(file)) as StackPanel;
root.Children.Add(panel);

Be sure you set the Build Action of the XAML file to Content, if you will use it as an resource. You can also pass directly a string with XAML code to the XamlReader.Load function.

Upvotes: 2

Related Questions