Define a DataTemplate in XAML?

Is it possible to define a DataTemplate in a XAML file and use it in code?

According to this answer: Silverlight: creating a DataTemplate in XAML and assigning it in code?

I can define it and add it to the resource dictionary in App.xaml, but I don't have the App.xaml file in my PCL project.

It sounds like a trivial thing, there should be a standard way to do it.

You can find an example DataTemplate here

+4
source share
1 answer

Yes, it is almost the same only x:Keyinstead x:Name.

<ContentPage.Resources>
    <ResourceDictionary>
      <DataTemplate x:Key="myTemplate"></DataTemplate>
    </ResourceDictionary>
</ContentPage.Resources>

and in your code on the page:

var myTemplate = (DataTemplate)Resources["myTemplate"];

App.xaml, . . https://github.com/xamarin/xamarin-forms-samples/tree/master/WorkingWithStyles

App.xaml:

  • App.xaml
  • partial App.cs
  • InitializeComponent() App
  • App.xaml
    • :
    • : MSBuild: UpdateDesignTimeXaml

:

App.xaml

<Application
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="App6.App">
    <Application.Resources>
        <ResourceDictionary>
            <DataTemplate x:Key="myTemplate"></DataTemplate>
        </ResourceDictionary>
    </Application.Resources>
</Application>  

App.cs

public partial class App : Application
{
    public App()
    {
        InitializeComponent();
        var myTemplate = (DataTemplate)Resources["myTemplate"];
        MainPage = new Page2();
    }

    protected override void OnStart()
    {
        // Handle when your app starts
    }

    protected override void OnSleep()
    {
        // Handle when your app sleeps
    }

    protected override void OnResume()
    {
        // Handle when your app resumes
    }
}
0

All Articles