简体   繁体   English

如何从资源字典文件访问事件处理程序?

[英]How do I access event handlers from resource dictionary file?

I have a resource dictionary file, in its .xaml.cs file I have an event handler like: 我有一个资源字典文件,在其.xaml.cs文件中,有一个事件处理程序,如:

private static bool OnlyNumbersAllowed(string text)
       {
           Regex regex = new Regex("[^0-9]+");
           return !regex.IsMatch(text);
       }

       private void PreviewTextInputHandlerInt(object sender, TextCompositionEventArgs e)
       {
           e.Handled = !OnlyNumbersAllowed(e.Text);
       }

While in the main window i want to access this code, like: 在主窗口中,我想访问此代码,例如:

<TextBox Name="Par5" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="357,36,0,0" Width="120" 
PreviewTextInput="{DynamicResource PreviewTextInputHandlerInt}"/>

Which won't work (the resource could not be resolved). 哪个行不通(资源无法解析)。 Also, I did some changes in dictionary root element, like: 另外,我对字典根元素进行了一些更改,例如:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    x:Class="network_app.Resources.ResDictionary"
                    x:ClassModifier="public">

I have access to this event handler from many other windows in my project, that's why I don't want to copy the code of event handler all over these windows in code-behind. 我可以从项目中的许多其他窗口访问此事件处理程序,这就是为什么我不想在代码隐藏的所有这些窗口中复制事件处理程序的代码的原因。 Is it possible somehow to access my event handler, declared in resource dictionary? 是否有可能以某种方式访问​​资源字典中声明的事件处理程序? Thanks. 谢谢。

Ok, I made this by adding this thing into resourcedictionary.xaml: 好的,我通过将这件事添加到resourcedictionary.xaml中来实现的:

<ControlTemplate x:Key="TextBoxInt">
    <TextBox PreviewTextInput="PreviewTextInputHandlerInt"/>
</ControlTemplate>

Then I accessed this in main window xaml like this: 然后,我在xaml主窗口中访问了此文件,如下所示:

<TextBox Template="{StaticResource TextBoxInt}" Name="Par5" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="357,36,0,0" Width="120" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM