How to change TextBox placeholder text color for a specific element, not global

后端 未结 2 1604
暖寄归人
暖寄归人 2021-01-12 18:38

MSDN lists the styles and templates for the TextBox class here. I can override these theme resources by creating a ResourceDictionary in App.

2条回答
  •  长发绾君心
    2021-01-12 19:15

    Old question I know, but I found it incredibly fruststrating that I had to create an entire copy of the TextBox style just to edit the placeholder color of one or two TextBox elements.

    So I created this method, which can be used on individual TextBoxes as required:

    public static void SetPlaceholderColor(TextBox textBox, Color color)
    {
        var textBoxContentGrid = VisualTreeHelper.GetChild(textBox, 0) as Grid;
        for (var i = 0; i < VisualTreeHelper.GetChildrenCount(textBoxContentGrid); i++)
        {
            var visualChild = VisualTreeHelper.GetChild(textBoxContentGrid, i);
            if ((string) visualChild.GetValue(FrameworkElement.NameProperty) != "PlaceholderTextContentPresenter") 
                continue;
            var placeHolderContentControl = visualChild as ContentControl;
            if (placeHolderContentControl != null)
                placeHolderContentControl.Foreground = new SolidColorBrush(color);
        }
    }
    

    This should also work for PasswordBoxes, since the TextBox parameter should easily be replacable with just "FrameworkElement"

提交回复
热议问题