Jimmy
Jimmy

Reputation: 3274

string reference binding in WPF

I have a binding in my view as follows

 <TextBox Grid.Row="3" Grid.Column="1" DataContext="{Binding FileStore}"  Text="{Binding Path=StoreId}" Foreground="Black"/>

FileStore.StoreId is a string. In my code I changed the StoreId at some point

FileStore.StoreId = "1234";

But the view is not updating the TextBox content. I could think of one possible reason-as string is immutable the assignment allocates a new string.So, the Textbox is still binding to the old instance. Do you agree? How can I tackle the situation?

Upvotes: 1

Views: 200

Answers (2)

zapico
zapico

Reputation: 2396

You should realize that FileStore is not changing (it's the same object), you can try by declaring a new FileStore with the new StoreId and then replace the current FileStore.

NewFileStore = new FileStoreType();
NewFileStore.StoreId="1234";
this.FileStore = NewFileStore;

Anyway, your FileStore class should be in a ViewModel which implements INotifyPropertyChanged.

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292695

Your FileStore class should implement INotifyPropertyChanged, so that the binding engine is notified when the value of a property is changed

class FileStore : INotifyPropertyChanged
{
    private string _storeId;

    public string StoreId
    {
        get { return _storeId; }
        set
        {
            _storeId = value;
            OnPropertyChanged("StoreId");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

Upvotes: 3

Related Questions