Xamarin.forms 是否可以获得对视图模型Xamarin表单的视图对象访问权限?

Xamarin.forms 是否可以获得对视图模型Xamarin表单的视图对象访问权限?,xamarin.forms,viewmodel,Xamarin.forms,Viewmodel,在我的应用程序中,所有视图模型都有一个基本视图模型类,我想在所有视图中添加几个常见视图。是否有任何方法可以在模型中识别其视图的对象,以便在其中添加公共子视图您可以使用ResourceDictionary定义ControlTemplate,然后将其作为StaticResource放入App.xaml 例如,公共视图是一个标签: 创建一个commonLabel.xaml: <ResourceDictionary xmlns="http://xamarin.com/schemas/20

在我的应用程序中,所有视图模型都有一个基本视图模型类,我想在所有视图中添加几个常见视图。是否有任何方法可以在模型中识别其视图的对象,以便在其中添加公共子视图

您可以使用
ResourceDictionary
定义
ControlTemplate
,然后将其作为
StaticResource
放入
App.xaml

例如,公共视图是一个
标签

创建一个
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>    
 <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>
然后您可以在页面中使用。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>


谢谢@LEO我已经尝试使用母版内容页实现此功能,并在需要时对其进行子类化。这是个好主意吗?@tarunsera是的,您还将内容页定义为基本页,然后让其他人对其进行子类化。