Search code examples
c#wpfwindowdatacontext

Access the main window datacontext from a new created window


In my MainWindow I create a new instance of a class containing different settings. After setting the parameters of the class, I set the datacontext = to that class.

public partial class MainWindow : Window
{

 private MeasConSettings mMeasConSettings = new MeasConSettings();

  public MainWindow()
  {
    InitializeComponent();
    DataContext = mMeasConSettings;
  }

  private void MenuComm_Click(object sender, RoutedEventArgs e)
  {// See code below}

}

Now I also have a function to open a new window, this window contains a textbox who's text should be bound to the datacontext of the MainWindow.

    private void MenuComm_Click(object sender, RoutedEventArgs e)
    {
        FrmSettings newWindow = new FrmSettings();
        newWindow.DataContext = mMeasConSettings;
        newWindow.TxtComm.Text = mMeasConSettings.CommSettings;
        newWindow.Show();
    }

This code fills in the textbox from the newWindow with the right content, BUT it does not get bound propery since the datacontext does not get updated after changing the text in the textbox (TxtComm in the new created window).

An example of the XAML code for the textbox:

<TextBox Grid.Row="1" Grid.Column="3" Margin="2,0"  Name="TxtComm" DataContext="{Binding Path=CommSettings, UpdateSourceTrigger=PropertyChanged}" />

"CommSettings" is a member of the MeasConsettings class

public class MeasConSettings
{
    private string mCommSettings;

    public string CommSettings
    {
        get
        {
            return mCommSettings;
        }
        set
        {
            mCommSettings = value;
        }
    }

    public MeasConSettings()
    {
        CommSettings = "Com5:19200,8,n,1";
    }
}

My problem is how can I adjust the value mMeasConSettings.CommSettings (defined in my MainWindow) in my newWindow (Which is created after pressing a button), If I change the textbox value in my newWindow, the value stored in mMeasConSettings.CommSettings should also be changed.

PS: I'm new to WPF so any advice is welcome!


Solution

  • As I wrote in the comment, you need to bind the Text property of your TextBox to the property of the DataContext which you want to update. Your XAML should thus be something like:

    <TextBox ... Text="{Binding CommSettings, Mode=TwoWay}" />
    

    Note that I am binding the Text property of the TextBox to the property CommSettings of your DataContext. And your C#-code for the click event should be:

    private void MenuComm_Click(object sender, RoutedEventArgs e)
    {
        FrmSettings newWindow = new FrmSettings();
        newWindow.DataContext = mMeasConSettings;
        newWindow.Show();
    }
    

    We only need to set the DataContext here. Note that the DataContext is passed along to child elements, so the TextBox will have the same DataContext as its parent unless specifically set to something else.