1
votes

Ok, I have a user control, which I want to transfer into a WPF custom control.

The user control has code behind file, so I can directly register to events of control: For Example:

<TextBox Grid.Column="0" 
                 Name="valueBox"                 
                 TextAlignment="Right" TextChanged="valueBox_TextChanged" PreviewKeyDown="valueBox_PreviewKeyDown" />

And the corresponding valueBox_TextChanged event in the code behind is:

 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));

    }

Now, when I try to turn this into a custom control, I have a Theme Folder, with a Generic.Xaml file. And file: MyCustomControl.cs

In Generic.Xaml, I've written (I derive from Control)

<TextBox Grid.Column="0" 
                 Name="valueBox"                 
                 TextAlignment="Right"  />

and in the cs file:

public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        AttachTextBox();
    }


 protected TextBox TextBox;

    private void AttachTextBox()
    {
        var textBox = GetTemplateChild("valueBox") as TextBox;

        if (textBox != null)
        {
            TextBox = textBox;
        }
    }

Now, how do I write a replacement for valueBox_TextChanged which is written in the user control?

1

1 Answers

0
votes

You can write the code for the valueBox_TextChanged event handler in the codebehind of your generic.xaml file. To create a code behind fiel for Generic.XAML follow the below steps.

  1. Add a file named generic.xaml.cs

    Right click on themes folder and select new class
    
    Name it as generic.xaml.cs
    
  2. Change the definition of the class inside generic.xaml.cs as partial class generic :ResourceDictionary //This class should inherit from ResourceDictionary
  3. Link this code behind file to Gereric.xaml by using x:Class

Now you can write code for your generic.xaml elements in the generic.xaml.cs file.

For More Info: Code behind for Generic.XAML