WPF Unable to retrieve binding values MVVM

前端 未结 1 889
礼貌的吻别
礼貌的吻别 2021-01-26 01:41

When I enter text into a Textbox, it updates two TextBlocks at the same time. I\'m trying to retrieve that value to save it to a sql database. I\'ve te

相关标签:
1条回答
  • 2021-01-26 02:13

    If you want both controls to share a DataContext then you can inject an instance from your composition root, i.e. App.Xaml.cs The following probably doesn't match the way your application is laid out but should give you the idea. Down the road you can look at dependency injection and how to compose your object graph but this a start.

    App.xaml

    <Application x:Class="App"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"                 
                 Startup="OnAppStartup">
        <Application.Resources>
    
        </Application.Resources>
    </Application>
    

    App.xmal.cs

    public partial class App : Application {
    
        private void OnAppStartup(object sender, StartupEventArgs e) {                        
            Application.Current.ShutdownMode = System.Windows.ShutdownMode.OnMainWindowClose;
            var vm = new PayslipModel();
            var mainWindow = new MainWindow(vm);
            Application.Current.MainWindow = mainWindow;
            mainWindow.Show();
        }
    }
    

    MainWindow.xaml.cs

    public MainWindow(PayslipModel vm){
        InitializeComponent();
        tabControl = new TabControl(vm);
        payRoll = new PayRoll(vm);
    }
    

    UserControls

    public TabLayout(PayslipModel vm)
    {
        InitializeComponent();
        DataContext = vm;
    }
    
    public Payroll(PayslipModel vm)
    {
        InitializeComponent();
        DataContext = vm;
    }
    
    0 讨论(0)
提交回复
热议问题