Eri*_*ric 13 wpf textbox mvvm selectedtext
我有一个带有ContextMenu的TextBox.当用户右键单击TextBox并选择适当的MenuItem时,我想在我的viewmodel中获取SelectedText.我还没有找到一种很好的方法来实现"MVVM"方式.
到目前为止,我的应用程序利用了Josh Smith的MVVM方式.我期待转移到Cinch.不确定Cinch框架是否会处理这样的问题.思考?
Tho*_*que 20
将SelectedText绑定到数据源没有直接的方法,因为它不是DependencyProperty ...但是,创建一个可以绑定的附加属性非常容易.
这是一个基本的实现:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以像在XAML中那样使用它:
<TextBox Text="{Binding Message}" u:TextBoxHelper.SelectedText="{Binding SelectedText}" />
Run Code Online (Sandbox Code Playgroud)