locked
Binding a UI item to an object property

    Question

  • Hello everybody.

    I have defined a class named DataManager which has a (String) property named ConnectionStatus. I am trying to bind a UI textbox (say connectionStatusTextBox) text to this property.

    In the XAML file I have 

    <TextBlock 
                Name="connectionStatusTextBox"
                Text="{Binding ConnectionStatus}"
                TextWrapping="NoWrap"
                />

    From the initializing method of the page, I am trying to set the DataContext for the TextBox:

    manager = ref new DataManager();

    this-> connectionStatusTextBox -> DataContext = manager;

    manager -> ConnectionStatus = "Hello world!"

    and have DataManager implement BindableBase from the Visual Studio templates. The setter method is then written

    void DataManager::ConnectionStatus::set(String ^ connectionStatus)
    {
    	if (_connectionStatus != connectionStatus) {	
    		_connectionStatus = connectionStatus;
    		OnPropertyChanged("ConnectionStatus");
    	}
    }

    But this does not work.

    Any ideas?

    Also, how does it need to be changed to work from a non-UI thread?

    Thanks in advance!

    Monday, July 22, 2013 12:08 PM

Answers

  • Did you apply the Bindable attribute to DataManager to enable it as a binding source?

    [Windows::UI::Xaml::Data::Bindable]
    public ref class DataManager sealed : YourApp::Common::BindableBase
    {
      ...

    In general you cannot access any XAML objects that derive from DependencyObject (including controls like TextBlocks, and I believe BindableBase) from a non-UI thread.  To update content on the UI thread from another thread, you can use an object's Dispatcher.

    Monday, July 22, 2013 4:17 PM

All replies

  • Did you apply the Bindable attribute to DataManager to enable it as a binding source?

    [Windows::UI::Xaml::Data::Bindable]
    public ref class DataManager sealed : YourApp::Common::BindableBase
    {
      ...

    In general you cannot access any XAML objects that derive from DependencyObject (including controls like TextBlocks, and I believe BindableBase) from a non-UI thread.  To update content on the UI thread from another thread, you can use an object's Dispatcher.

    Monday, July 22, 2013 4:17 PM
  • Thanks Jesse, that was a careless mistake on my part.
    Wednesday, July 24, 2013 8:14 AM