views:

102

answers:

2

Hi !

I want to derive from System.Windows.Controls.TextBox and provide this functionality.

IsEnabledProperty.OverrideMetadata(typeof(MyTextBox), new FrameworkPropertyMetadata(
            new PropertyChangedCallback(delegate(DependencyObject o, DependencyPropertyChangedEventArgs e)
            {
                MyTextBox tb = o as MyTextBox;

                if (tb != null && !tb.IsEnabled)
                {
                    tb.SetValue(TextProperty, null);
                    tb.OnLostFocus(new RoutedEventArgs(LostFocusEvent, typeof(MyTextBox)));
                }
            }
            )));

The problem is that if I write a Custom Control, nothing will be displayed when using it, but I don't want to write my custom Template. I want to use the original one.

How would you do that, please ?

+2  A: 

Check and see if your control overrides the DefaultStyleKeyProperty

DefaultStyleKeyProperty.OverrideMetadata

If that is the case, it will expect to find a style somewhere. Remove that override and you should be seeing normal TextBox behaviour!

If it does not, you can always base your new Textbox style on your old style, like so:

<Style TargetType="{x:Type Your:YourTextBox}" BasedOn="{StaticResource {x:Type TextBox}}" />

Place it in a ResourceDictionary somewhere, and it should work as well!

Hope this helps!

Arcturus
Yep, you're right, I didn't notice it overwrites the Template somewhere in the Class. Thank you !
PaN1C_Showt1Me
You're welcome ;)
Arcturus
A: 

There is a much simpler option, here. Just use a DataTrigger to set your TextBox's Text to null (or empty) when the TextBox.IsEnabled is false:

<Style TargetType="TextBox">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=IsEnabled}" Value="False">
           <Setter Property="Text" Value="" />
        </DataTrigger>
    </Style.Triggers>
</Style>
Reed Copsey