我为项目使用浮动导航菜单,因此我需要在每个页面中使用它
<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"
我需要克服此代码重复,因此任何人都可以建议一种方法来实现
答案 0 :(得分:2)
在xaml资源字典中创建模板资源,然后将其导入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>
然后,将此模板应用于您的页面:
<ContentPage ControlTemplate={StaticResource PageTemplate}>
...
</ContentPage>
如果愿意,可以创建一个基本的contentpage类,并在构造函数中可以这样做:
public abstract class BasePage : ContentPage
{
public BasePage()
{
SetDynamicResource(ControlTemplateProperty, "PageTemplate");
}
...
}
这样做,从BasePage继承的页面将自动应用模板。您可能还想在此基础页面类中定义绑定到NavigationMenu的属性。