简体   繁体   English

将变量绑定到Windows Phone 8中的文本块

[英]Binding variable to a textblock in Windows Phone 8

In XAML, i have a textblock 在XAML中,我有一个文本块

<TextBlock x:Name="block" Text="{Binding b1}"/>

and in c# i created a property 在C#中我创建了一个属性

public int _b1;
public int b1
    {
        get { return _b1; }
        set
        {
            _b1 = value;
        }
    }

public MainPage()
{
    InitializeComponent();
    block.DataContext = this;
}

this worked fine, textblock show the _b1. 这工作正常,textblock显示_b1。 But when i add a button to chage the _b1 variable 但是当我添加一个按钮来改变_b1变量时

private void bt_click(object sender, RoutedEventArgs e)
    {
        _b1 = 4; 
    }

the textblock didn't update ????? 文本块没有更新??????

For UI to update automatically upon property value change, your property needs to either be a DependencyProperty or your class needs to implement INotifyPropertyChanged interface. 为了使UI在属性值更改时自动更新,您的属性必须是DependencyProperty或您的类需要实现INotifyPropertyChanged接口。

For creating a DependencyProperty, you could use Visual Studio's propdp snippet (type propdp inside your class and press Tab) and fill in respective values. 若要创建DependencyProperty,可以使用Visual Studio的propdp代码段(在类内部键入propdp并按Tab),然后填写相应的值。 If you want to go INotifyPropertyChanged path, you'll need to write the following code in the setter of your property (AFTER setting the value of _b1 ): 如果要转到INotifyPropertyChanged路径,则需要在属性的设置器中编写以下代码(在设置_b1的值_b1 ):

if(PropertyChanged != null)
    PropertyChanged(this, new PropertyChangedEventArgs("b1"));

To add to dotNet's answer (which is the correct answer), use a baseclass where you implement INotifyPropertyChanged if you want to avoid redundand code: (this is one example, there are other ways to implement this) 要添加到dotNet的答案(这是正确的答案)中,如果要避免重复代码,请在实现INotifyPropertyChanged的地方使用基类:(这是一个示例,还有其他方法可以实现此目的)

  public abstract class BindableBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
    {
        if (Equals(storage, value)) { return false; }

        storage = value;
        OnPropertyChanged(propertyName);
        return true;
    }

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var eventHandler = PropertyChanged;
        if (eventHandler != null)
        {
            eventHandler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

And use it like so: 并像这样使用它:

class MyClass: BindableBase
{
        private int _b1;
        public int B1
        {
            get { return _b1; }
            set { SetProperty(ref _b1, value); }
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM