using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Input; using System.Windows.Media; namespace SSPCTester.UI.Views; public partial class SettingsManualView : UserControl { public SettingsManualView() => InitializeComponent(); private void SaveSettingsClicked(object sender, RoutedEventArgs e) { if (!IsLoaded) return; CommitAllBindings(); if (DataContext is ViewModels.SettingsViewModel vm) vm.NotifyDraftChanged(); } private void DraftChanged(object sender, RoutedEventArgs e) { if (!IsLoaded) return; UpdateBindingSource(sender); if (DataContext is ViewModels.SettingsViewModel vm) vm.NotifyDraftChanged(); } private static void UpdateBindingSource(object sender) { if (sender is ComboBox comboBox) { comboBox.GetBindingExpression(Selector.SelectedValueProperty)?.UpdateSource(); comboBox.GetBindingExpression(Selector.SelectedItemProperty)?.UpdateSource(); comboBox.GetBindingExpression(ComboBox.TextProperty)?.UpdateSource(); } else if (sender is TextBox textBox) { textBox.GetBindingExpression(TextBox.TextProperty)?.UpdateSource(); } else if (sender is ToggleButton toggleButton) { toggleButton.GetBindingExpression(ToggleButton.IsCheckedProperty)?.UpdateSource(); } } private void CommitAllBindings() { // Ensure the currently focused editor pushes its latest value first. if (Keyboard.FocusedElement is FrameworkElement focused) UpdateFrameworkElementBindings(focused); foreach (var element in EnumerateVisuals(this).OfType()) UpdateFrameworkElementBindings(element); } private static IEnumerable EnumerateVisuals(DependencyObject root) { int count = VisualTreeHelper.GetChildrenCount(root); for (int i = 0; i < count; i++) { var child = VisualTreeHelper.GetChild(root, i); yield return child; foreach (var nested in EnumerateVisuals(child)) yield return nested; } } private static void UpdateFrameworkElementBindings(FrameworkElement element) { switch (element) { case TextBox textBox: textBox.GetBindingExpression(TextBox.TextProperty)?.UpdateSource(); break; case ComboBox comboBox: comboBox.GetBindingExpression(Selector.SelectedValueProperty)?.UpdateSource(); comboBox.GetBindingExpression(Selector.SelectedItemProperty)?.UpdateSource(); comboBox.GetBindingExpression(ComboBox.TextProperty)?.UpdateSource(); break; case ToggleButton toggleButton: toggleButton.GetBindingExpression(ToggleButton.IsCheckedProperty)?.UpdateSource(); break; default: if (element is Selector selector) { selector.GetBindingExpression(Selector.SelectedValueProperty)?.UpdateSource(); selector.GetBindingExpression(Selector.SelectedItemProperty)?.UpdateSource(); } break; } if (element.BindingGroup != null) element.BindingGroup.UpdateSources(); } }