从 cs 中获取变量并在 xaml (uwp) 中使用它

本文关键字:uwp 获取 cs 变量 xaml | 更新日期: 2023-09-27 18:31:42

如何在 XAML 文件中使用 C# 字符串的值?

这是我的代码部分:CS 文件

public sealed partial class SomePage : Page
    {
        public SomePage ()
        {
            AppVersion = "some text" + XDocument.Load ("WMAppManifest.xml").Root.Element ("App").Attribute ("Version").Value.ToString();
            this.InitializeComponent ();
        }
        public string AppVersion{get; set;}

XAML 文件:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
     EntranceNavigationTransitionInfo.IsTargetElement="True">
        <StackPanel>
             <TextBlock x:Name="VersionTextBlock" Text="{Binding ElementName=VersionTextBlock, FallbackValue= AppVersion}"/>

从 cs 中获取变量并在 xaml (uwp) 中使用它

您的绑定引用了TextBlock,这不是您的AppVersion所在位置。由于AppversionPage上的一个属性,因此可以使用编译时绑定,如下所示:

<TextBlock Text="{x:Bind AppVersion}"/>

另一方面,动态绑定是相对于Page DataContext的,这意味着如果要执行此操作:

<TextBlock Text="{Binding AppVersion}"/>

。您必须将PageDataContext设置为具有名为 AppVersion 的属性的某个对象,例如,

public SomePage ()
{
    AppVersion = "some text" + ...;
    InitializeComponent ();
    DataContext = this; // More common is to have a separate viewmodel class, though.
}