|
| 1 | +using System.Windows; |
| 2 | +using System.Windows.Data; |
| 3 | +using System.Windows.Input; |
| 4 | + |
| 5 | +namespace WebsiteCreator.Core |
| 6 | +{ |
| 7 | + public static class InputBindingsManager |
| 8 | + { |
| 9 | + |
| 10 | + public static readonly DependencyProperty UpdatePropertySourceWhenEnterPressedProperty = DependencyProperty.RegisterAttached( |
| 11 | + "UpdatePropertySourceWhenEnterPressed", typeof(DependencyProperty), typeof(InputBindingsManager), new PropertyMetadata(null, OnUpdatePropertySourceWhenEnterPressedPropertyChanged)); |
| 12 | + |
| 13 | + static InputBindingsManager() |
| 14 | + { |
| 15 | + |
| 16 | + } |
| 17 | + |
| 18 | + public static void SetUpdatePropertySourceWhenEnterPressed(DependencyObject dp, DependencyProperty value) |
| 19 | + { |
| 20 | + dp.SetValue(UpdatePropertySourceWhenEnterPressedProperty, value); |
| 21 | + } |
| 22 | + |
| 23 | + public static DependencyProperty GetUpdatePropertySourceWhenEnterPressed(DependencyObject dp) |
| 24 | + { |
| 25 | + return (DependencyProperty)dp.GetValue(UpdatePropertySourceWhenEnterPressedProperty); |
| 26 | + } |
| 27 | + |
| 28 | + private static void OnUpdatePropertySourceWhenEnterPressedPropertyChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e) |
| 29 | + { |
| 30 | + if (dp is not UIElement element) |
| 31 | + { |
| 32 | + return; |
| 33 | + } |
| 34 | + |
| 35 | + if (e.OldValue != null) |
| 36 | + { |
| 37 | + element.PreviewKeyDown -= HandlePreviewKeyDown; |
| 38 | + } |
| 39 | + |
| 40 | + if (e.NewValue != null) |
| 41 | + { |
| 42 | + element.PreviewKeyDown += new KeyEventHandler(HandlePreviewKeyDown); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + private static void HandlePreviewKeyDown(object sender, KeyEventArgs e) |
| 47 | + { |
| 48 | + if (e.Key == Key.Enter) |
| 49 | + { |
| 50 | + DoUpdateSource(e.Source); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + private static void DoUpdateSource(object source) |
| 55 | + { |
| 56 | + DependencyProperty property = |
| 57 | + GetUpdatePropertySourceWhenEnterPressed((DependencyObject)source); |
| 58 | + |
| 59 | + if (property == null) |
| 60 | + { |
| 61 | + return; |
| 62 | + } |
| 63 | + |
| 64 | + |
| 65 | + if (source is not UIElement elt) |
| 66 | + { |
| 67 | + return; |
| 68 | + } |
| 69 | + |
| 70 | + BindingExpression binding = BindingOperations.GetBindingExpression(elt, property); |
| 71 | + |
| 72 | + if (binding != null) |
| 73 | + { |
| 74 | + binding.UpdateSource(); |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments