我正在使用ControlTemplate
在Android和iOS上具有一致的导航栏
<ControlTemplate x:Key="NavBarTemplate">
<StackLayout>
<StackLayout Orientation="Horizontal"
VerticalOptions="CenterAndExpand"
IsVisible="{TemplateBinding BindingContext.IsBackButtonVisible, Mode=TwoWay}">
<Label Text="<"
FontSize="Large"
FontAttributes="Bold"
HorizontalTextAlignment="Center"
VerticalOptions="FillAndExpand"
VerticalTextAlignment="Center"
Margin="20,0,0,0" />
<Label TextColor="{StaticResource DarkGrey}"
HorizontalOptions="StartAndExpand"
HorizontalTextAlignment="Center"
VerticalOptions="FillAndExpand"
VerticalTextAlignment="Center"
FontSize="Small"
Text="Back" />
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Command="{TemplateBinding BindingContext.NavigateBackCommand}" />
</StackLayout.GestureRecognizers>
</StackLayout>
<Image Source="logo.png"
VerticalOptions="Center" />
</StackLayout>
</ControlTemplate>
为了动态显示后退按钮,我在OnAppearing
的BasePage.cs
中添加了以下代码:>
protected override void OnAppearing () { base.OnAppearing (); if (BindingContext is BaseViewModel viewmodel) { if(Application.Current.MainPage as NavigationPage nav) { if(nav.Navigation.NavigationStack.Count >1 ) { viewmodel.IsBackButtonVisible = true; }else { viewmodel.IsBackButtonVisible = false; } //dirty coding force to false if (!this.IsBackButtonVisible) //refers to local BindableProperty { viewmodel.IsBackButtonVisible = false; } }else //no viewmodel found just use localbinding { BindingContext = this; } } }
因此,在某些页面中,即使
NavigationStack
为>1
,我仍要强制执行后退按钮
现在,通过在BasePage中将BindableProperty
命名为相同的IsBackButtonVisible
,我正在基于上面的脏编码实现
我的问题是,有没有办法为ControlTemplate
做替代绑定,我知道正常绑定有FallBackValue和Default(它们只是没有绑定的值),但是我不想对其进行硬编码,并且TemplateBinding并没有支持那些(智能不会显示这些选项)
我想做的是将BindableProperty
中的BasePage
重命名为ForceNoBackButton
,并且尽管有ViewModel绑定,但导航栏还是不可见。
根据条件,是否有任何方法可以在TemplateBinding
中进行替代绑定。
如果BindingContext是BaseViewModel的类型,则使用属性IsBackButtonVisible
否则,如果页面BindingContext
是此页面或不是BaseViewModel
,则回退到BasePage
本地BindableProperty
,即ForceNoBackButton
我可以使用BindableProperty的propertychanged事件处理程序吗?如果是,如何。我知道如果可视元素位于当前XAML中,该怎么做,不知道如何针对TemplatedView
我正在使用ControlTemplate的Android和iOS上具有一致的导航栏
public static readonly BindableProperty ForceNoBackButtonProperty =
BindableProperty.Create(
"ForceNoBackButton", typeof(bool), typeof(BasePage),
defaultValue: default(bool));
public static readonly BindableProperty IsBackButtonVisibleProperty =
BindableProperty.Create(
"IsBackButtonVisible", typeof(bool), typeof(BasePage),
defaultValue: default(bool));
并更新您的控件模板以仅使用IsBackButtonVisible
<ControlTemplate x:Key="NavBarTemplate"> ... <StackLayout Orientation="Horizontal" .. IsVisible="{TemplateBinding IsBackButtonVisible}">
[如下修改
OnAppearing()
方法时: