我发现了这个问题,可以帮助我实现部分想做的事情:MVVM-如何在文本框中选择文本?
我的第一个问题是我有两个文本框,每个文本框都有一个“全选”按钮,但是我无法弄清楚如何调整已接受的答案,以便可以独立控制每个文本框。
另外,我想为每个按钮添加一个“复制所选文本”按钮。
在坚持MVVM模式的同时如何做到这一点?
您可以将两个按钮绑定到不同的命令,这些命令在不同的文本框上调用工作,也可以使用commandParameters区分要处理的文本。
您可以通过创建AttachedProperty来跟踪链接的帖子,也可以只进行自定义控件。本质上,您需要做的是为文本选择创建一个可绑定的属性。TextBox的属性“ SelectedText”听起来不错,但是如果您尝试在WPF中绑定它,则它会抛出错误,因为它不是DependencyProperty。属性必须是DependencyProperty,您才能绑定到该属性。
因此,您创建了一个,例如IsTextSelected作为bool,当它发生更改时,您的AttachedProperty或自定义控件将对其进行处理并执行SelectAll()或SelectedText = Text;
如果做单个项目,我建议使用AttachedProperty。但是,您要求使用自定义控件,我认为,如果对一种类型的控件进行多项功能改进,则不应使用这些控件,而不能在其他类型的控件上重复使用它们。
public class SmartTextBox : TextBox
{
public static readonly DependencyProperty IsSelectedTextProperty = DependencyProperty.RegisterAttached("IsSelectedText",
typeof(bool), typeof(SmartTextBox), new FrameworkPropertyMetadata(false, OnIsSelectedChanged));
public bool IsSelectedText
{
get { return (bool)GetValue(IsSelectedTextProperty); }
set { SetValue(IsSelectedTextProperty, value); }
}
private static void OnIsSelectedChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
SmartTextBox textbox = sender as SmartTextBox;
if ((bool)e.NewValue)
{
textbox.Focus();
textbox.SelectAll();
}
}
}
用法:ViewModel
set
因此您可以随时强制使用它,而不必跟踪用户的操作。注意2设置多个属性IsSelectedUsername,IsSelectedFilepath等,并将其绑定。每个SmartTextBox都绑定到一个,并将处理该更改。
public bool IsSelectedText
{
get { return isSelectedText; }
set
{
isSelectedText = value;
RaisePropertyChanged("IsSelectedText");
}
}
private void SelectAllExecute()
{
IsSelectedText = true;
}
用法:XAML
xmlns:custom="clr-namespace:xyz.View.Controls"
<custom:SmartTextBox Text="{Binding Path=MyText}"
IsSelectedText="{Binding Path=IsSelectedText}"/>
检索选定的文本,您需要向自定义控件中添加可以绑定到的新依赖项属性,以及控件进行更新的方式。我选择控件何时离开焦点而不是更改选择,因为我希望用户在知道所需的文本之前先执行一下单击按钮之类的操作。
public static readonly DependencyProperty SelectedText2Property = DependencyProperty.RegisterAttached("SelectedText2",
typeof(string), typeof(SmartTextBox), new PropertyMetadata(""));
public string SelectedText2
{
get { return (string)GetValue(SelectedText2Property); }
set { SetValue(SelectedText2Property, value); }
}
protected override void OnLostFocus(RoutedEventArgs e)
{
SelectedText2 = this.SelectedText;
base.OnLostFocus(e);
}
XAML现在已将其绑定:
<custom:SmartTextBox Text="{Binding Path=MyText}"
SelectedText2="{Binding Path=TheSelectedText, Mode=OneWayToSource}"
IsSelectedText="{Binding Path=IsSelectedText}"/>
ViewModel具有一个愚蠢的属性(因为它是OneWayToSource,因此无需引发change事件)
public string TheSelectedText { get; set; }
随处可以做
Console.WriteLine(TheSelectedText);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句