cod*_*oop 61 c# wpf events textbox
我创建了一个自定义控件继承TextBox
.此自定义控件是数字TextBox
,仅支持数字.
我OnPreviewTextInput
用来检查每个键入的新字符,看看该字符是否是有效的输入.这非常有效.但是,如果我将文本粘贴到TextBox
,OnPreviewTextInput
则不会被触发.
捕获粘贴文本的最佳方法是TextBox
什么?
此外,我在按下后退空间时遇到问题,我无法弄清楚这将触发什么事件.OnPreviewTextInput
没被解雇!
有关如何在WPF中捕获粘贴文本和后台空间事件的任何想法TextBox
?
Mat*_*ton 123
以下是我曾经需要的一些代码.可能会帮助你.
public Window1()
{
InitializeComponent();
// "tb" is a TextBox
DataObject.AddPastingHandler(tb, OnPaste);
}
private void OnPaste(object sender, DataObjectPastingEventArgs e)
{
var isText = e.SourceDataObject.GetDataPresent(DataFormats.UnicodeText, true);
if (!isText) return;
var text = e.SourceDataObject.GetData(DataFormats.UnicodeText) as string;
...
}
Run Code Online (Sandbox Code Playgroud)
Ray*_*rns 14
尝试拦截和捕获可能导致TextBox.Text属性更改的所有单个事件的问题是,有许多此类事件:
试图可靠地拦截所有这些是徒劳的.一个更好的解决方案是监视TextBox.TextChanged并拒绝您不喜欢的更改.
在这个答案中,我展示了如何为被询问的特定场景实现TextBoxRestriction类.可以推广使用相同的技术,以便与要放置在TextBox控件上的任何限制一起使用.
例如,在您的情况下,您可以实现与该代码中的RestrictValidChars
属性类似的附加属性RestrictDeleteTo
.它将是相同的,除了内循环将检查插入,而不是删除.它会像这样使用:
<TextBox my:TextBoxRestriction.RestrictValidChars="0123456789" />
Run Code Online (Sandbox Code Playgroud)
这只是一个如何处理它的想法.根据您的需要,有许多方法可以构建代码.例如,您可以更改TextBoxRestriction以调用您自己的代码,以使用附加属性进行验证,该属性接受委托或包含事件的对象.
有关如何在使用TextBoxRestriction类时绑定Text属性的详细信息,请参阅其他答案,以便在您不希望它时不会触发限制.
对于退格键,请检查PreviewKeyDown事件
对于paste命令,将命令绑定添加到ApplicationCommands.Paste,如果您不想对其执行任何操作,请将参数设置为processed:
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Paste"
Executed="PasteExecuted" />
</Window.CommandBindings>
Run Code Online (Sandbox Code Playgroud)
在代码背后:
private void PasteExecuted(object sender, ExecutedRoutedEventArgs e)
{
e.Handled = true;
}
Run Code Online (Sandbox Code Playgroud)