user3448806
user3448806

Reputation: 907

Binding variable to a textblock in Windows Phone 8

In XAML, i have a textblock

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

and in c# i created a property

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. But when i add a button to chage the _b1 variable

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

the textblock didn't update ?????

Upvotes: 0

Views: 1455

Answers (2)

Iris Classon
Iris Classon

Reputation: 5842

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)

  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); }
        }
}

Upvotes: 3

dotNET
dotNET

Reputation: 35450

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.

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. 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):

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

Upvotes: 3

Related Questions