【问题标题】:Binding variable with TextBlock使用 TextBlock 绑定变量
【发布时间】:2015-06-29 06:49:48
【问题描述】:

我的 XAML 代码(在标准空白页模板的 Page 内)为

<Grid>
  <TextBlock x:Name="tbBindingBlock">
</Grid>

我在代码隐藏中有一个名为 iTestBindingint。是否有一种简单的(因为我只绑定一个变量而不是集合)方法将两者绑定在一起,以便 iTestBinding 的最新值(不断从代码隐藏中更改)始终显示在 @987654327 内@?


编辑:后面的代码很短:

public sealed partial class MainPage : Page
{
    public int iTestBinding=0;

【问题讨论】:

标签: c# xaml windows-store-apps microsoft-metro winrt-xaml


【解决方案1】:

您可以使用以下代码直接绑定您的值

<TextBlock x:Name="tbBindingBlock" Text="{Binding iTestBinding}">

保持你的值在这样的代码中作为属性绑定

      public int iTestBinding{ get; set; }

并像这样在页面加载事件中设置数据上下文

      this.DataContext = this;

如果你想更新按钮点击的值并反映在 UI 中,你需要实现 PropertyChangedEventHandler。

 public event PropertyChangedEventHandler PropertyChanged;
 private void RaisePropertyChanged(string propertyName)
    {
        // take a copy to prevent thread issues
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

在您更新属性值的任何位置调用 RaisePropertyChanged("changed property name")。

最好为属性保留一个自定义的 get 设置,以便我们可以从 setter.for 中调用此方法

    private string myText;
    public string MyText { 
        get {
            return myText;
    }
        set {
            myText = value;
            RaisePropertyChanged("MyText");
        }
    }

【讨论】:

  • 感谢您的回复。在这种情况下,datacontext 将设置为什么?
  • 如果您的页面中没有其他绑定,您可以将 iTestBinding 设置为数据上下文。
  • 是的,我试过了,但页面上什么也没有显示(文本块显示为空)。
  • 是的,我编辑了这个问题。后面的代码中没有其他内容(只有一些代码在用户单击按钮时将变量增加 + 1)。
  • 它没有(文本框中没有显示文本),但感谢您提供帮助。我怀疑这可能与 Metro 与 WPF 中的绑定差异有关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-09
  • 2014-09-07
  • 1970-01-01
  • 2014-08-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多