Non esiste un modo semplice per associare SelectedText a un'origine dati, perché non è una proprietà di dipendenza ... tuttavia, è piuttosto facile creare una proprietà associata che è possibile associare.
Ecco un'implementazione di base:
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);
}
}
}
È possibile quindi utilizzarlo come quella in XAML:
<TextBox Text="{Binding Message}" u:TextBoxHelper.SelectedText="{Binding SelectedText}" />
fonte
2010-02-11 17:14:41
Grazie !! Questo ha fatto il trucco. Così ovvio e l'ho perso. Grazie ancora. – Eric
Sto cercando di fare lo stesso per la proprietà CaretIndex ma sembra che non funzioni. Potete aiutare – TheITGuy
@TheITGuy, non senza vedere il vostro codice ... Probabilmente dovreste creare una nuova domanda (potete postare il link qui, risponderò se posso) –