locked
Inherit textbox control wpf RRS feed

  • Question

  • Hi!

    I'm going to make som special rules to some of my textboxes. So I thought I'd create a new class, that inherits the textbox. And put the new rules for the OnKeyDown event there, so it can be reused. 

    public class MyTextBox : TextBox
    {
    protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs e)
    {
    if (e.KeyData == System.Windows.Forms.Keys.Enter )
    {

    //do something!
    }
    }
    }


    But I'm unable to figure out how I can get the new OnKeyDown apply to my textbox in my xaml file??

    Anybody who has done this?? I've search without result!!

    Hope someone can help!!
    Thanks! Carina
    Wednesday, October 15, 2008 9:31 AM

Answers

  • Do you now use your MyTextBox in xaml instead of the standard TextBox? Also make sure that you have the xml namespace registered and are using the prefix with your MyTextBox. Like this:

    <Window x:Class="[your namespace here].Window1" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:local="clr-namespace:[your namespace here]" 
        Title="Window1" Height="300" Width="300">  
          
        <Grid> 
              
            <local:MyTextBox Text="TEST"/>  
     
        </Grid> 
    </Window> 

    If your custom textbox is in another project you will have to change the xml namespace (and optionally the prefix) to for example:

    <Window x:Class="[your namespace here].Window1" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:controls="clr-namespace:[your control project namespace here];assembly=[your control project assemblyname here]" 
        Title="Window1" Height="300" Width="300">  
          
        <Grid> 
              
            <controls:MyTextBox Text="TEST"/>  
     
        </Grid> 
    </Window> 

    hth,
    Marcel
    • Edited by DutchMarcel Wednesday, October 15, 2008 11:22 AM corrected xml namespace placeholders
    • Marked as answer by Marco Zhou Tuesday, October 21, 2008 10:57 AM
    Wednesday, October 15, 2008 11:21 AM