好的,我有一个用户控件,我想把它转移到WPF自定义控件中。
用户控件在文件后面有代码,所以我可以直接注册到控件的事件:例如:
<TextBox Grid.Column="0"
Name="valueBox"
TextAlignment="Right" TextChanged="valueBox_TextChanged" PreviewKeyDown="valueBox_PreviewKeyDown" />
后面代码中对应的valueBox_TextChanged事件是:
private void valueBox_TextChanged(object sender, TextChangedEventArgs e)
{
var textBox = (TextBox)sender;
var positiveWholeNum = new Regex(@"^-?d+$");
if (!positiveWholeNum.IsMatch(textBox.Text) || int.Parse(textBox.Text) < 0)
{
textBox.Text = "0";
}
NumericValue = Convert.ToInt32(textBox.Text);
RaiseEvent(new RoutedEventArgs(ValueChangedEvent));
}
现在,当我试图把它变成一个自定义控件,我有一个主题文件夹,与通用。Xaml文件。MyCustomControl.cs
通用。Xaml,我已经写了(我从Control派生)
<TextBox Grid.Column="0"
Name="valueBox"
TextAlignment="Right" />
和cs文件中的
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
AttachTextBox();
}
protected TextBox TextBox;
private void AttachTextBox()
{
var textBox = GetTemplateChild("valueBox") as TextBox;
if (textBox != null)
{
TextBox = textBox;
}
}
现在,我如何编写valueBox_TextChanged的替代品,这是在用户控件中编写的?
您可以在泛型的代码后面编写valueBox_TextChanged事件处理程序的代码。xaml文件。为Generic创建一个代码隐藏字段。XAML遵循以下步骤。
-
添加一个名为generic. example .cs的文件
Right click on themes folder and select new class Name it as generic.xaml.cs
- 将generic. example .cs中的类定义更改为partial类generic:ResourceDictionary//这个类应该继承自ResourceDictionary
-
将此代码文件链接到generic。使用x:Class
现在可以为泛型编写代码了。在generic.xaml.cs文件中的Xaml元素。
查看更多信息:泛型的代码。XAML