【发布时间】:2014-06-21 08:42:47
【问题描述】:
好的,我有一个用户控件,我想将其转换为 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));
}
现在,当我尝试将其转换为自定义控件时,我有一个主题文件夹,其中包含一个 Generic.Xaml 文件。和文件:MyCustomControl.cs
在 Generic.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 编写替换?
【问题讨论】: