【问题标题】:Transfer User Control to a WPF custom control将用户控件转移到 WPF 自定义控件
【发布时间】: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 编写替换?

【问题讨论】:

    标签: wpf xaml controls


    【解决方案1】:

    您可以在 generic.xaml 文件的代码隐藏中编写 valueBox_TextChanged 事件处理程序的代码。要在 Generic.XAML 的字段后面创建代码,请按照以下步骤操作。

    1. 添加一个名为 generic.xaml.cs 的文件

      Right click on themes folder and select new class
      
      Name it as generic.xaml.cs
      
    2. 将 generic.xaml.cs 中的类定义更改为部分定义 class generic :ResourceDictionary //这个类应该继承自 资源字典
    3. 使用 x:Class 将此代码隐藏文件链接到 Gereric.xaml

    现在您可以在 generic.xaml.cs 文件中为您的 generic.xaml 元素编写代码。

    欲了解更多信息:Code behind for Generic.XAML

    【讨论】:

      猜你喜欢
      • 2011-09-10
      • 1970-01-01
      • 1970-01-01
      • 2011-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多