我正在使用 Xamarin.Forms 开发一个新的非常基本的应用程序,我有一个疑问......我无法弄清楚如何做到这一点,因为我对 Xamarin 没有太多经验。
我有一个 ContentPage
我适合的地方ContentView
根据我单击的选项卡,更改第一个中的导航标题很容易,因为我可以使用 Title="[introduce any title]"
但我在 View 上没有这个属性。
这基本上是我的代码,我添加了我想要添加的 View 的命名空间,如下所示:
<ContentPage
...
xmlns:views="clr-namespace:Your.Name.Space"
...>'
然后在我的页面内容中,我可以像这样使用它:
<views:NameOfView />
我正在为底部导航使用自定义选项卡布局。
我希望你们中的任何人都可以采取正确的方式。
谢谢。
最佳答案
推荐的实现方法是使用 PageTitle
View 模型上的属性 - 与当前内容 View 保持同步;以及相应的标题。
但是,如果您只想在 View 级别实现此功能;那么你可以通过引入一个绑定(bind)模式为OneWayToSource
的自定义可绑定(bind)属性来做到这一点。在您的内容 View 中。例如:
public class NavigationView : ContentView
{
public static readonly BindableProperty TitleProperty =
BindableProperty.Create("Title",
typeof(string),
typeof(NavigationView),
defaultValue: null,
defaultBindingMode: BindingMode.OneWayToSource);
public string Title
{
get => (string)GetValue(TitleProperty);
set => SetValue(TitleProperty, value);
}
}
并且,将您的自定义属性绑定(bind)到
ContentPage
标题使用自我引用。例如:<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
....
x:Name="_self"
Title="{Binding Path=Content.Title, Source={x:Reference _self}}">
或者,将绑定(bind)添加到自定义 View 以充分利用绑定(bind)模式:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
...
x:Name="_self">
...
<local:NavigationView Title="{Binding Path=Title, Source={x:Reference _self}}">
使用示例
XAML:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:TitleView"
x:Class="TitleView.TitleViewPage"
x:Name="_self"
Title="{Binding Path=Content.Title, Source={x:Reference _self}}">
<local:NavigationView Title="This is page-1">
<Button Text="Go to page-2" Clicked="Handle_Clicked" />
</local:NavigationView>
</ContentPage>
代码隐藏:
public partial class TitleViewPage : ContentPage
{
void Handle_Clicked(object sender, System.EventArgs e)
{
this.Content = new NavigationView {
Title = "This is page-2",
Content = new Button { Text = "Go back to page-1", IsEnabled = false } };
}
public TitleViewPage()
{
InitializeComponent();
}
}
编辑 1:还添加了一些代码来说明如何定义从内容 View 到页面的绑定(bind)。
关于xamarin.forms - ContentView发生变化时如何动态改变导航栏标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45834558/