You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MAUI中如何将FlyoutFooterTemplate内Label值设为应用版本

解决FlyoutFooterTemplate中Label绑定应用版本的问题

有两种简单方案可以实现需求:

方法一:直接绑定静态属性

利用{x:Static}标记扩展直接引用AppShell的静态AppVersion属性,步骤如下:

  1. 在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">
  1. 修改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绑定实例属性

如果更倾向于实例属性绑定,可按以下步骤操作:

  1. 在AppShell.xaml.cs中定义实例属性(保留静态属性也可,但实例绑定更贴合常规绑定逻辑):
public string AppVersion { get; } = AppInfo.Current.VersionString;
  1. 给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">
  1. 在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 20:42:29