Für das Markieren des Texts einer TextBox gibt es extra das SelectedText-Property. Beim Einsetzen des MVVM-Entwurfsmusters (Model View ViewModel) möchte man ein eigenes SelectedText-Property vom ViewModel mit der TextBox per Data Binding zusammenbringen. Leider ist das gar nicht so einfach möglich. Das Problem hierbei ist, dass das TextBox.SelectedText-Property kein Dependency-Property ist.
Eine elegante Lösung dazu ist das Schreiben eines eigenen Attached Property. Es erweitert die TextBox um diese fehlende Funktionalität. Ändert sich der Wert, wird ebendieser der TextBox direkt an das reguläre Property zugewiesen. In Listing 1 wird der Code für das Attached Property gezeigt. Eingesetzt wird er wie folgt:
<TextBox Text="{Binding Text}" local:TextBoxHelper.SelectedText="{Binding SelectedText}" />
Das Ergebnis ist in Abbildung 1 zu sehen.
public static class TextBoxHelper { public static string GetSelectedText(DependencyObject obj) { return (string)obj.GetValue(SelectedTextProperty); } public static void SetSelectedText(DependencyObject obj, string value) { obj.SetValue(SelectedTextProperty, value); } public static readonly DependencyProperty SelectedTextProperty = DependencyProperty.RegisterAttached( "SelectedText", typeof(string), typeof(TextBoxHelper), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, SelectedTextChanged)); private static void SelectedTextChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { TextBox textBox = obj as TextBox; if (textBox != null) { if (e.OldValue == null && e.NewValue != null) { textBox.SelectionChanged += OnSelectionChanged; } else if (e.OldValue != null && e.NewValue == null) { textBox.SelectionChanged -= OnSelectionChanged; } string newValue = e.NewValue as string; if (newValue != null && newValue != textBox.SelectedText) { textBox.SelectedText = newValue as string; } } } static void OnSelectionChanged(object sender, RoutedEventArgs e) { TextBox textBox = sender as TextBox; if (textBox != null) { SetSelectedText(textBox, textBox.SelectedText); } } }