使用继承在TextBox上进行双向SelectedText绑定 [英] Two-way SelectedText binding on TextBox using inheritance
问题描述
我试图通过绑定自定义属性"Selected"将TextBox的SelectedText替换为新值.当前,通过绑定更新Selected不会更改实际的SelectedText.我想我快到了;至少鼠标选择文本正在更新选定".
I'm trying to replace the SelectedText of a TextBox with a new value by binding on the custom property 'Selected'. Currently, updating Selected through binding doesn't change the actual SelectedText. I'm almost there I think; at least mouse-selecting text is updating Selected.
如果可能的话,我希望基于从TextBox继承的解决方案.有人可以告诉我缺少什么吗?
I'd prefer solutions based on inheriting from TextBox if possible. Can anybody tell me what's missing please?
class SelectionTextbox : TextBox
{
public static readonly DependencyProperty SelectionProperty = DependencyProperty.Register("Selection", typeof(string), typeof(SelectionTextbox));
public string Selection
{
get
{
return (string)base.GetValue(SelectionProperty);
}
set
{
base.SetValue(SelectionProperty, value);
}
}
protected override void OnSelectionChanged(RoutedEventArgs e)
{
base.OnSelectionChanged(e);
Selection = SelectedText;
}
}
推荐答案
问题是,您永远不会对分配给选择
的值进行任何操作.您实际上需要将其设置为选定的文本.
The problem is, that you never actually do anything with the value you assign to Selection
. You need to actually make it the selected text.
public string Selection
{
get
{
return (string)base.GetValue(SelectionProperty);
}
set
{
base.SetValue(SelectionProperty, value);
if(value != SelectedText)
SelectedText = value;
}
}
这篇关于使用继承在TextBox上进行双向SelectedText绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!