首页 > 解决方案 > 是否可以让视图对象访问视图模型 Xamarin 表单?

问题描述

在我的应用程序中,所有视图模型都具有基本视图模型类,我想向所有具有视图模型的视图添加一些通用视图。有什么方法可以在模型中识别其视图的对象是什么,以便我可以将公共子视图添加到其中

标签: xamarin.formsviewmodel

解决方案


你可以定义一个ControlTemplatewith ResourceDictionary,然后把它App.xaml作为一个StaticResource.

例如,常见的视图是Label

创建一个commonLabel.xaml

<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    >

     <ControlTemplate x:Key="testcontrol">
         <Label Text="this is a common label"/>
     </ControlTemplate>

</ResourceDictionary>    

然后在你的App.xaml

 <Application xmlns="http://xamarin.com/schemas/2014/forms"
     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
     x:Class="YourProject.App">
     <Application.Resources>

        <ResourceDictionary Source="commonLabel.xaml"/>

     </Application.Resources>
 </Application>

那么你可以在你的 pages.xaml 中使用:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
     NavigationPage.HasNavigationBar="false"
     ControlTemplate="{StaticResource BaseTemplate}"
     x:Class="YourPage">

     <ContentView ControlTemplate="{StaticResource testcontrol}"/>

</ContentPage>

推荐阅读