Creating Windows Store App Pages Without XAML

戏子无情 提交于 2020-01-11 05:09:04

问题


I am writing a C#/XAML Windows Store app and would like to create and navigate to and display a Page entirely from C#. Is this possible? Obviously I can inherit from Page, but, when attempting to Navigate to a derived Page that has no XAML, I get a System.TypeLoadException... "Could not find Windows Runtime type 'Windows.Foundation'".

My thought was this should be possible since XAML translates into a CLR partial class definition, so there's no reason one couldn't do everything in C#. But obviously I missing some sort of framework requirement.

Suggestions?

Right now all I have for the derived Page is

using Windows.UI.Xaml.Controls;

namespace App1 {
    public class Page2 : Page {
        public Page2 () { }
    }
}

And here is the full exception:

Could not find Windows Runtime type 'Windows.Foundation'.
at System.StubHelpers.WinRTTypeNameConverter.GetTypeFromWinRTTypeName(String typeName, Boolean& isPrimitive)
at System.StubHelpers.SystemTypeMarshaler.ConvertToManaged(TypeNameNative* pNativeType, Type& managedType)
at Windows.UI.Xaml.Controls.Frame.Navigate(Type sourcePageType)
at App1.MainPage.<P2>d__2.MoveNext()

回答1:


I can give an example for a simple page

using System;
using Windows.ApplicationModel.Activation;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
namespace MyApp
{
    class Program
    {
        public static void Main (string[] args)
        {
            Application.Start((p) => new MyApp());
        }
    }
    class MyApp : Windows.UI.Xaml.Application
    {
        public MyApp(){}
        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            var layoutRoot = new Grid() { Background = new SolidColorBrush(Colors.Blue) };
            layoutRoot.Children.Add(new Button() { Content = "Hello!" });
            Window.Current.Content = layoutRoot;
            Window.Current.Activate();
        }
    }
}

Replace these paths with the correct items when compiling:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /target:appcontainerexe /r:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Runtime.WindowsRuntime.dll" /r:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Runtime.dll" /r:"C:\Windows\System32\WinMetadata\windows.applicationmodel.winmd" /r:"C:\Windows\System32\WinMetadata\windows.ui.winmd" /r:"C:\Windows\System32\WinMetadata\windows.ui.xaml.winmd" /r:"C:\Windows\System32\WinMetadata\windows.media.winmd" MyApp.cs



回答2:


You can create dynamic XAML using LINQ and XML.

Here's an example on how to create a dynamic TextBlock; you can use the concept to apply it to a Page element:

http://msdn.microsoft.com/en-us/library/cc189044(v=vs.95).aspx



来源:https://stackoverflow.com/questions/22662723/creating-windows-store-app-pages-without-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!