开发者

Override default value of TextBox.TextProperty

I have a custom control that derives from TextBox. And I cannot find a way to override the default Text 开发者_高级运维value. So, in short - I want MyTextBox to have some specific default text in it.

The code:

    public class MyTextBox : TextBox
    {
        static MyTextBox()
        {
            TextBox.TextProperty.OverrideMetadata(
                typeof(MyTextBox), 
                new FrameworkPropertyMetadata("DEFAULT TEXT", OnTextChanged));
        }

        private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
        }
    }

The problem is that the property (strangely) contains the "DEFAULT TEXT" value, yet it does not show up in the UI (text box is empty).

What am I doing wrong?


The TextBox uses an inner class to provide most of it's functionality. This same class is shared with RichTextBox. I believe the TextBox assumes Text will be empty when constructed, so the UI is not updated.

One thing to keep in mind is that you have effectively short-circuited the TextBox.OnTextPropertyChanged method from being called. If you want to override the PropertyChangedCallback, then you'd probably need to manually call the TextBox version to ensure everything works as expected.

You can get to the base class's PropertyChangedCallback using TextProperty.GetMetadata(typeof(TextBox)).PropertyChangedCallback.

You may be able to call the TextBox's PropertyChangedCallback in an instance constructor to force the UI to update. Otherwise, you'd need to set Text directly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜