Natalie
Natalie

Reputation: 471

Bind a WPF mainWindow TextBox to a variable calculated in a user control C#

I have a textBox on my main Window and I have a user control with Images (Bitmaps). Through a mouse click on an Image, a value is calculated. This value should be displayed on the textBox in the main window. 1) without data binding How could I access the textBox object on the main window from the user control. It works the other way round, i.e. I can access a user control textBox from the main window using the name of the user control and the textBox to access the textBox such as usercontrol1.textBoxName. But it seems to me that I cannot access a main window textBox from the usercontrol such as mainWindow.textBoxName because the user control does not know the main Window and has no main Window object. Is this correct? 2) with data binding It probably works with data binding. But what I tried so far did not work. In the main window XAML:

TextBox  Text="{Binding Path=usercontrol1.GetCycleNumber()}"   Name="cycleNumberBox" 

in mainWindow.cs:

public partial class MainWindow : Window , INotifyPropertyChanged 

I added the INotifyPropertyChanged

public event PropertyChangedEventHandler PropertyChanged;
private  void RaisePropertyChanged(string propertyName)
  {
      PropertyChangedEventHandler handler = this.PropertyChanged;
      if (handler != null)
        {
          handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public  void CycleChanged()
    {
      this.cycleNumber = usercontrol1.GetCycleNumber();
            if (this.cycleNumberBox.Text != cycleNumber)
            {
              this.cycleNumberBox.Text = cycleNumber;
               RaisePropertyChanged("cycleNumber");

         }

  }

usercontrol1.cs Now I would have to signal a change with

RaisePropertyChanged("cycleNumber"); 

in the user control. However, I cannot access this method. Since I spent days already to figure this out, I would be glad for any help. I am beginner and it is my first project. Thank you!

Upvotes: 0

Views: 2325

Answers (1)

SergioL
SergioL

Reputation: 4963

If you have a user control that needs to share a piece of data with main window (or for any container of the user control), your best bet is to use data binding.

  1. Expose a dependency property on the user control. In your case, it looks like CycleNumber.

Internally,the user control can use this dependency property as needed. If it's a calculated field, you may want to use the RegisterReadOnly() method to register the dependency property.

2a. To have other controls access the value in CycleNumber, you can either use ElementBinding to bind to the dependency property, or

2b. have the dependency propery bound to a value in your ViewModel (or other structure if you're not following the MVVM pattern).

If you need more to go on, I can come up with some sample code for you.

Hope that helps. Sergio

Upvotes: 1

Related Questions