如何减少导航菜单中的代码重复 [英] how to reduce the code duplication in my navigation menu

查看:96
本文介绍了如何减少导航菜单中的代码重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用浮动导航菜单,因此我需要在每个页面中使用它

I use a floating navigation menu for my project so I need it in every single page this is my code

  <customRenderes:NavigationImageButton Source="IconFAB"
                                          x:Name="NavigationImageButton"
                                          ItemTapped="NavigationImageButton_OnItemTapped"

                                AbsoluteLayout.LayoutFlags="PositionProportional"
                                AbsoluteLayout.LayoutBounds="1.0,1.0,-1,-1"
                                Margin="10"
                                Opacity="0.4"

我需要克服此代码重复,因此任何人都可以建议一种方法来实现

I need to overcome this code duplication so can anyone suggest a way to do this

推荐答案

在xaml资源字典中创建模板资源,然后将其导入App.xaml:

Create a template resource in a xaml resource dictionary which you import in App.xaml:

<ResourceDictionary ... />
  <ControlTemplate x:Key="PageTemplate">
    <Grid>
      <!-- Any pages with content that use this template will display contents in this ContentPresenter -->
      <ContentPresenter />
      <!-- Add elements common to all pages, TemplateBinding looks at the code behind for properties on the page being displayed through this template -->
      <FloatingNavigationMenu Contents={TemplateBinding MenuContents} />
    </Grid>
  </ControlTemplate>
</ResourceDictionary>

然后,将此模板应用于您的页面:

Then, apply this template to your pages:

<ContentPage ControlTemplate={StaticResource PageTemplate}>
  ...
</ContentPage>

如果愿意,您可以创建一个基本的contentpage类,并在构造函数中可以执行以下操作:

If you wanted to, you could create a base contentpage class, and in the constructor you could do:

public abstract class BasePage : ContentPage
{
  public BasePage()
  {      
    SetDynamicResource(ControlTemplateProperty, "PageTemplate");
  }
  ...
}

这样做,从BasePage继承的页面将自动应用模板.您可能还希望在此基础页面类中定义绑定到NavigationMenu的属性.

Doing this, pages inheriting from BasePage will automatically have the template applied. You would probably want to define your properties that are bound to your NavigationMenu in this base page class as well.

这篇关于如何减少导航菜单中的代码重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆