locked
Proper way to do page navigation. RRS feed

  • Question

  • I'm creating a WPF desktop application. I have a MainWindow. Inside the MainWindow I currently have a Frame that will host all of my pages. I am using myFrame.Navigate(PageToNavigateTo) in my CommandBinding Executed method when clicking a radio button. There are 8 radio buttons, one for each page. I am hiding the navigate next/back with this: NavigationUIVisibility="Hidden"


    This all works well and I can change pages when clicking the radio buttons. How can I bind content inside my frame's pages to elements on my MainWindow that are outside the frame? For example, lets say on page8 is loaded in myFrame . If I have a TextBox on that page and type some text in it. I want a label sitting outside of the frame on my MainWindow to update with that text. How can I do this? I try setting the DataContext of the frame and that doesn't work. I have a sample app working up to this point and could post it somewhere if that would help. Thanks in advance.

    Thursday, September 2, 2010 12:59 PM

Answers

  • Hi BBauer42,

    The DataBinding cannot across the Page to the Window domain. But we can set the DataContext of the Page instance (not the Frame) and create the DataBinding for the TextBox in the Page. Such as:

     public partial class Window1 : Window
     {
      public Window1()
      {
       InitializeComponent();
       Page1 page = new Page1();
       MyClass myclass = new MyClass();
       page.DataContext = myclass;
       this.DataContext = myclass;
       frame.Navigate(page);
      }
     }
    
     public class MyClass : INotifyPropertyChanged
     {
      private string _name;
      public string Name
      {
       get { return _name; }
       set
       {
        _name = value;
        if (PropertyChanged != null)
         PropertyChanged(this, new PropertyChangedEventArgs("Name"));
       }
      }
    
      public event PropertyChangedEventHandler PropertyChanged;
     }
    

    Then in the Window, create a DataBinding for the label with the MyClass instance:

     <Grid>
      <Grid.RowDefinitions>
       <RowDefinition Height="Auto"/>
       <RowDefinition Height="*"/>
      </Grid.RowDefinitions>
      <Label Content="{Binding Name}" />
      <Frame x:Name="frame" Grid.Row="1"/>
     </Grid>
    

    The XAML of the Page1:

     <Grid>
      <TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"/>
     </Grid>
    

    Hope this helps.

    Sincerely,

    Bob Bao

    MSDN Subscriber Support in Forum 

    If you have any feedback on our support, please contact msdnmg@microsoft.com


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    • Marked as answer by BBauer42 Friday, September 3, 2010 12:32 PM
    Friday, September 3, 2010 5:43 AM