Data Binding between two TextBoxes in different windows

前端 未结 4 2051
傲寒
傲寒 2021-01-14 04:00

I have created a program that changes the name in a TextBox when check or unckeck a Checkbox. I want to replicate this Textbox in a different window. I thought with Data Min

4条回答
  •  粉色の甜心
    2021-01-14 04:11

    You will have to pass a reference to either the first window or the object that you're updating the text property on to the second window, it's DataContext property will do for that, you can then bind the second windows controls to it.

    In this demo application I've created a MainWindow and a second window (Window1), the application starts in Main window like this.

    MainWindow.xaml.cs

    public partial class MainWindow : Window
    {
        public string TestString
        {
            get { return (string)GetValue(TestStringProperty); }
            set { SetValue(TestStringProperty, value); }
        }
    
        public static readonly DependencyProperty TestStringProperty =  DependencyProperty.Register("TestString", typeof(string), typeof(MainWindow), new UIPropertyMetadata(null));
    
        public MainWindow()
        {
            InitializeComponent();
    
            // setup the test string.
            TestString = "this is a test.";
    
            // Create the second window and pass this window as it's data context.
            Window1 newWindow = new Window1()
            {
                DataContext = this
            };
            newWindow.Show();
        }
    }
    

    MainWindow.xaml - Take note of the DataContext line in the Window declaration.

    
        
            
        
    
    

    Now for Window1 the code behind is just an empty default window class so I won't post it but the xaml is.

    Window1.xaml

    
        
            
        
    
    

提交回复
热议问题