【问题标题】:How to bind data from code behind to a WPF Label, from XAML?如何从 XAML 将代码后面的数据绑定到 WPF 标签?
【发布时间】:2015-05-04 15:44:21
【问题描述】:

我见过一些类似的问题,但没有一个对我来说足够简单。我已经用 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 的最简单最简单的方法是什么?

这编译和运行良好,但标签是空白的原因,显然我敢肯定,这回避了我。

【问题讨论】:

  • 这并不是真正的代码背后。隐藏代码定义为在 Window1.xaml.cs 文件中找到的代码。每个 .xaml 文件都有一个 .xaml.cs 代码隐藏文件。
  • Window1后面的代码是Window1类中定义的代码?
  • 是的,Window1.xaml.cs 是 Window1.xaml 背后的代码。

标签: c# wpf xaml binding


【解决方案1】:

由于您使用的是staticclass,因此您必须在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绑定它

&lt;Label Content="{Binding [0], Source={x:Static local:Globals.Things}}"/&gt;

【讨论】:

  • 完美运行。如果有,我可以修复它,但出于好奇,让 getter 返回这样的新数组是否存在任何潜在的内存管理问题?我经常使用这个数组,每次调用它都会创建全新的、相对较大的数组吗?它是将整个数组保存在内存中,还是只保存我调用它的元素?
  • 对初始化一次值的属性使用私有支持字段。 getter 可以返回支持字段。我更新了我的答案以反映这一点。
  • 正如李所说,使用支持字段。我已经更新了我的答案。看看吧。
【解决方案2】:

有几个问题。

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

【讨论】:

  • '对 STUFF.Globals 类型的构造函数的调用,匹配指定的绑定约束引发了异常。'行号“12”和行位置“4”。 ---> System.ArgumentException:数组不能为空。你知道它为什么会告诉我这个吗?
  • 我要么必须把它变成一个非静态类,才能像上面提到的那样使用 StaticResource 和键。或者摆脱资源部分并直接绑定到静态类,就像 Anand 在他的回答中所做的那样。
  • 谢谢。我选择了另一个答案,因为我需要重写很多东西才能使它成为非静态的。
  • 不用担心。很高兴我能帮上忙!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-15
  • 2015-11-03
  • 1970-01-01
  • 1970-01-01
  • 2018-12-08
  • 2013-11-27
  • 2015-11-07
相关资源
最近更新 更多