如何在WPF中将代码绑定到变量后面 [英] How to bind code behind variables in WPF

查看:278
本文介绍了如何在WPF中将代码绑定到变量后面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将string类型的变量绑定到labals的Content控件.关于使用转换器进行绑定以及不同种类的绑定的任何帮助,将不胜感激.

我尝试过的事情:

我尝试过将Window属性绑定到自身,并尝试通过简单地绑定到变量来访问变量后面的代码,例如:
XAML代码

I''m trying to bind a variable of type string to a labals Content control. Any help regarding binding using converters and different kinds of binding would be appreciated.

What I have tried:

I''ve tried is binding the Window property to itself and trying to access code behind variables by simple binding to them as such:
XAML code

<Window DataContext="{RelativeSource Self}" >
    <Label Content="{Binding Path=Hello}"/>
</Window>


C#代码


C# code

public partial class MainWindow : Window
{
    string Hello = "Hello World";
    public MainWindow()
    {
    }
}


这确实可以编译,但不会显示任何内容.


This does compile but wont display anything. Any feedback would be appriciated.

推荐答案

Hello既是private也是 field .
这些都将破坏绑定.
它必须是public(或internal)属性.
试试:
Hello is both private and a field.
Either of those will break a binding.
It needs to be a public (or internal) property.
Try:
public partial class MainWindow : Window
{
    private const string HelloMessage = "Hello World";
    public string Hello { get { return HelloMessage; } }

    public MainWindow()
    {
    }
}



============
MTH-2016年4月29日

以允许Label更新更改的方式显示对属性的绑定:
XAML:



=============
MTH - April 29, 2016

Showing binding to a property in such a way as to allow for the Label to update on changes:
XAML:

<Window>
    <Label Content="{Binding Path=Hello}"/>
</Window>

C#:

using System.ComponentModel;
using System.Runtime.CompilerServices;
public partial class MainWindow : Window, INotifyPropertyChanged
{
  public MainWindow()
  {
    InitializeComponent();
    DataContext = this;
  }
  private string _Hello = "Select Workflow Variant:";
  public string Hello
  { 
    get { return _Hello; }
    set
    { 
      _Hello = value;
      OnPropertyChanged();
    }
  }
  #region INotifyPropertyChanged Members

  public event PropertyChangedEventHandler PropertyChanged;

  /// <summary>
  /// Raises this object's PropertyChanged event.
  /// </summary>
  /// <param name="propertyName">The property that has a new value.</param>
  protected void OnPropertyChanged([CallerMemberName]string propertyName = null)
  {
    PropertyChangedEventHandler handler = this.PropertyChanged;
    if (handler != null)
    {
      var e = new PropertyChangedEventArgs(propertyName);
      handler(this, e);
    }
  }
  #endregion
}


现在,如果更改了Hello属性,则将更新Label.类似地定义其他可设置的属性.


Now, if the Hello property is changed, the Label will be updated. Define other settable properties similarly.


这篇关于如何在WPF中将代码绑定到变量后面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆