No hay una forma directa de enlazar SelectedText a una fuente de datos, porque no es una DependencyProperty ... sin embargo, es bastante fácil crear una propiedad adjunta que podría enlazar.
Aquí es una implementación básica:
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);
}
// Using a DependencyProperty as the backing store for SelectedText. This enables animation, styling, binding, etc...
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 tb = obj as TextBox;
if (tb != null)
{
if (e.OldValue == null && e.NewValue != null)
{
tb.SelectionChanged += tb_SelectionChanged;
}
else if (e.OldValue != null && e.NewValue == null)
{
tb.SelectionChanged -= tb_SelectionChanged;
}
string newValue = e.NewValue as string;
if (newValue != null && newValue != tb.SelectedText)
{
tb.SelectedText = newValue as string;
}
}
}
static void tb_SelectionChanged(object sender, RoutedEventArgs e)
{
TextBox tb = sender as TextBox;
if (tb != null)
{
SetSelectedText(tb, tb.SelectedText);
}
}
}
entonces Se puede utilizar como esa en XAML:
<TextBox Text="{Binding Message}" u:TextBoxHelper.SelectedText="{Binding SelectedText}" />
Gracias! Esto hizo el truco. Tan obvio y me lo perdí. Gracias de nuevo. – Eric
Estoy tratando de hacer lo mismo para la propiedad CaretIndex, pero parece que no está funcionando. Puede ayudar – TheITGuy
@TheITGuy, no sin ver su código ... Probablemente debería crear una nueva pregunta (puede publicar el enlace aquí, le responderé si puedo) –