MAUI中如何将FlyoutFooterTemplate内Label值设为应用版本
有两种简单方案可以实现需求:
方法一:直接绑定静态属性
利用{x:Static}标记扩展直接引用AppShell的静态AppVersion属性,步骤如下:
- 在XAML根节点(Shell标签)添加命名空间声明,替换为你的应用实际命名空间:
<Shell xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:YourAppNamespace" <!-- 替换为你的应用命名空间 --> x:Class="YourAppNamespace.AppShell">
- 修改Label的Text属性,绑定静态属性:
<Label x:Name="lblVersion" Text="{x:Static local:AppShell.AppVersion}" TextColor="Red" FontAutoScalingEnabled="True" FontSize="Body" VerticalOptions="EndAndExpand" HorizontalOptions="Center" Margin="10"/>
方法二:通过BindingContext绑定实例属性
如果更倾向于实例属性绑定,可按以下步骤操作:
- 在AppShell.xaml.cs中定义实例属性(保留静态属性也可,但实例绑定更贴合常规绑定逻辑):
public string AppVersion { get; } = AppInfo.Current.VersionString;
- 给Shell标签设置
x:Name:
<Shell x:Name="appShell" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="YourAppNamespace.AppShell">
- 在DataTemplate的Grid中设置BindingContext为Shell实例,再绑定属性:
<DataTemplate> <Grid ColumnDefinitions="0.8*,0.2*" Padding="10" BindingContext="{x:Reference Name=appShell}"> <Label x:Name="lblVersion" Text="{Binding AppVersion}" TextColor="Red" FontAutoScalingEnabled="True" FontSize="Body" VerticalOptions="EndAndExpand" HorizontalOptions="Center" Margin="10"/> </Grid> </DataTemplate>
为什么之前的尝试失败?
DataTemplate的默认BindingContext并非AppShell实例,直接绑定AppShell的属性会找不到数据源。通过{x:Static}指定静态属性,或者手动将BindingContext指向AppShell实例,就能解决这个问题。
内容的提问来源于stack exchange,提问作者astorcas
相关产品推荐
相关产品推荐

