Mwspencer
Mwspencer

Reputation: 1183

WPF Xaml Change TextBox Trigger Change Foreground

I have a TextBox style. I am trying to make a Placeholder(I realized I am not the first to ask about this.) However I found a very uncomplicated way that works for my needs. Once the user clicks in the box the "email" is removed.

    public  void email_input_Click(object sender, System.EventArgs e)
    {
        if(email_input.Text == "email")
        {
            email_input.Text = "";
        }
    }

Now for the font. My default text color is grey. I would like this to turn Black when the user starts typing. I am new to xaml and wpf and cannot figure out the trigger to do so.

    <!-- Placeholder -->
    <Style x:Key="PlaceHolder" TargetType="TextBox">
        <Setter Property="TextAlignment" Value="Center"/>
        <Setter Property="VerticalAlignment" Value="Top"/>
        <Setter Property="HorizontalAlignment" Value="Center"/>
        <Setter Property="Height" Value="30"/>
        <Setter Property="Width" Value="340"/>
        <Setter Property="FontSize" Value="16"/>
        <Setter Property="Foreground" Value="Gray"/>
        <Setter Property="Background" Value="White"/>
        <Setter Property="BorderBrush" Value="Black"/>
        <Setter Property="BorderThickness" Value="0.5"/>
        <Setter Property="FontWeight" Value="Light"/>
        <Style.Triggers>
            <Trigger Property="PreviewMouseDown" Value="True">
                <Setter Property="Foreground" Value="Black"/>
                <Setter Property="FontWeight" Value="Medium"/>
            </Trigger>
        </Style.Triggers>
    </Style>

Property="PreviewMouseDown" is not recognized or not accessible. Why is it not accessible, and what trigger can I use instead?

Edit: This seemed to work, though I'm not sure how robust.

public  void email_input_Click(object sender, System.EventArgs e)
{
    if(email_input.Text == "email")
    {
        email_input.Text = "";
    }

    email_input.Foreground = Brushes.Black;
    email_input.FontWeight = FontWeights.SemiBold;            

}

Upvotes: 1

Views: 1963

Answers (1)

Sudsy1002
Sudsy1002

Reputation: 598

This should be what you are looking for:

<Trigger Property="IsKeyboardFocused" Value="True">
            <Setter Property="Foreground" Value="Black"/>
            <Setter Property="FontWeight" Value="Medium"/>
</Trigger>

PreviewMouseDown is not a property, its an event, which is why you are getting the message. IsKeyboardFocused is a property that should accomplish what you want. For a list of properties, see TextBox.

Note: This will also set the text back to grey once the user has left focus. If this is not what you want, let me know and I'll update this answer.

Upvotes: 1

Related Questions