【问题标题】:how to set binding for the label in wpf如何在wpf中为标签设置绑定
【发布时间】:2011-08-12 22:17:24
【问题描述】:

我需要将属性绑定到标签。我写了以下代码: 标签的 xml 是

<Label Canvas.Left="807.3" Canvas.Top="148.9" Height="33.567" x:Name="label2"
       Width="98" FontFamily="Tw Cen MT" FontSize="24" FontWeight="Bold"
       Foreground="#FFFEE3A4"
       Content="{Binding Path=UserInformation.AccountBalance,Mode=OneWay}">
    <Label.Background>
        <ImageBrush />
    </Label.Background>
</Label>

拥有 AccountBalance 的类

public class CustomerInformation : INotifyPropertyChanged
    {
        public CustomerInformation()
        {
            _Balance = 0.0;
        }

        #region INotifyPropertyChanged Members
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion

 public double AccountBalance
        {
            get { return _Balance; } 
        set 
        {
            _wepaBalance = value;
            FirePropertyChanged("AccountBalance");
        } 

        }

 protected void FirePropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
}

datacontext 设置如下

this.LayoutRoot.DataContext = this;

在 xaml.cs 后面编写了以下代码来访问作为全局对象的 UserInfo

public CustomerInformation UserInformation
        {
            get
            {

                return Globalobjs._Object.UserInfo;
            }
        }

xamls.cs 仅派生自 Window。

问题是INotifyPropertyChanged的PropertyChangedEventHandler在调用时总是为null。

任何一位可以帮助我解决这个问题吗?

【问题讨论】:

  • 你能把src代码也发一下吗?
  • 你将DataContext设置在哪里?您能否还为NotifyChanged 实现添加代码?
  • 当然是 VoodooChild 和 Townsean。感谢您的关注。

标签: c# wpf xaml data-binding


【解决方案1】:
this.LayoutRoot.DataContext = this; 

这是Window,但您将Window 实例设置为DataContext。将DataContext 设置为UserInformation。

this.LayoutRoot.DataContext = Globalobjs._Object.UserInfo;

【讨论】:

  • 我有其他控件绑定到窗口的不同属性。
  • @logeeks 用 LayoutRoot 的父级设置 LayoutRoot.DataContext 没有意义;你确实意识到这一点,不是吗?
【解决方案2】:

您要绑定的数据上下文是否实现了 INotifyPropertyChanged?

如果这不是 MVVM 模式项目,请确保包含您要绑定的属性的类实现了该接口,并确保在您更改属性时调用事件的委托(例如 OnPropertyChanged("MyProperty "))

如果它是一个 MVVM 项目并且您没有使用框架,最好从实现 INotifyPropertyChanged 的​​ ViewModel 基础派生所有 ViewModel。

【讨论】:

  • Thanks.AccountBalance 是实现 INotifyPropertyChanged 的​​全局对象的成员。我正在使用包含 AccountBalance 的类的代码更新帖子。
【解决方案3】:

您正在绑定到 Windows 的 DataContext。但是 Windows DataContext 与后面的 Windows 代码不同,您在其中定义了 UserInformation 属性。要访问在后面的 Window 代码中定义的属性,您必须设置 Window 的 Name 属性,然后改用以下绑定:

Content="{Binding ElementName=YourWindowName, Path=UserInformation.AccountBalance,Mode=OneWay}"

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 2011-06-07
    • 2010-12-27
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 2017-07-24
    相关资源
    最近更新 更多