如何将来自XAML的WPF标签的数据绑定到WPF标签



我已经看到了一些类似的问题,但是没有一个对我来说足够愚蠢。我已经在C#中编码了大约两个星期,并且使用WPF大约两天。

我有一个类

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

和一个窗口

<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绑定到XAML的最简单最简单的简便方法是什么?

这可以编译并运行良好,但由于原因,标签是空白的,很明显,我敢肯定,逃避了我。

由于您使用的是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是静态类,因此您必须使用x:Static

  3. 绑定它

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

有几个问题。

  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}}"/>
    

最新更新