如何将来自 XAML 的数据从代码绑定到 WPF 标签?

How to bind data from code behind to a WPF Label, from XAML?

我见过几个类似的问题,但是 none 对我来说已经足够愚蠢了。我用 C# 编写代码大约两周,使用 WPF 大约两天。

我有一个class

namespace STUFF
{
    public static class Globals
    {
        public static string[] Things= new string[]
        {   
            "First Thing"
        };
    }
}

和一个window

<Window
    x:Class="STUFF.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    xmlns:local="clr-namespace:STUFF"
    Title="STUFF"
    Height="600"
    Width="600">
<Window.Resources>
    <local:Globals x:Key="globals"/>
</Window.Resources>
<Grid>
    <Label Content="{Binding globals, Path=Things[0]}"/>
</Grid>

从 XAML 内部将代码后面的数据绑定到 XAML 的最简单最简单的方法是什么?

编译并运行良好,但标签是空白的,原因很明显,我敢肯定,这让我难以理解。

有几个问题。

  1. 您只能绑定到属性,不能绑定到字段。将事物定义更改为

    private readonly static string[] _things = new string[] { "First Thing" };
    public static string[] Things { get { return _things; } }
    
  2. 绑定应将全局列为源。将绑定更改为此

    <Label Content="{Binding Path=Things[0], Source={StaticResource globals}}"/>
    

由于您使用的是 static class,因此您必须在 xaml 中提及您的来源 x:Static

  1. 将您的字段更改为 属性

    private string[] _Things;
    
    public string[] Things
    {
        get
        {
    
            if (_Things == null)
            {
                _Things = new string[] { "First Thing", "Second Thing" };
            }
            return _Things;
        }
    }
    
  2. 因为Globals是静态的class,你必须使用x:Static

  3. 绑定它

<Label Content="{Binding [0], Source={x:Static local:Globals.Things}}"/>