简体   繁体   中英

Changing text in textblock to italicized on MouseEnter

I have a textblock that contains some non-italicized text. When the mouse enters the textblock, the text changes through the use of the code behind. I would like the code behind to also have the ability to change the text to italicized. This is what I have so far:

XAML:

<TextBlock x:Name="block1"
   Background="Cyan"
   Foreground="{StaticResource myBrush2}"
   Grid.Column="0"
   Grid.Row="0"
   Height="30"
   HorizontalAlignment="Center"
   MouseEnter="TextBlock_MouseEnter"
   MouseLeave="TextBlock_MouseLeave"
   Padding="0,7,0,0"
   Text ="Hover Me!"
   TextAlignment="Center"
   Width="100"/>

Code Behind (C#):

public void TextBlock_MouseEnter(object sender, MouseEventArgs e)
{
    string blockName = ((TextBlock)sender).Name;
    var block = sender as TextBlock;
    if (block != null && blockName == "block1")
    {
        block.Text = "Yo! I'm TextBlock1";
    }
}

I have looked into using System.Drawing and the use of FontStyle.Italic; although I was unsuccessful of actually making it work.

This is what XAML was made for

<TextBlock x:Name="block1"
   Background="Cyan"
   Foreground="{StaticResource myBrush2}"
   Grid.Column="0"
   Grid.Row="0"
   Height="30"
   HorizontalAlignment="Center"
   MouseEnter="TextBlock_MouseEnter"
   MouseLeave="TextBlock_MouseLeave"
   Padding="0,7,0,0"
   Text ="Hover Me!"
   TextAlignment="Center"
   Width="100">
            <TextBlock.Style>
            <Style TargetType="TextBlock">
                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="FontStyle" Value="Italic" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
        </TextBlock>

But, if you really want to, here's an example of how you might implement that functionality from code-behind.

private void block1_MouseEnter(object sender, MouseEventArgs e)
{
     SetFontStyle(FontStyles.Italic);
}

private void block1_MouseLeave(object sender, MouseEventArgs e)
{
     SetFontStyle(FontStyles.Normal);
}
private void SetFontStyle(FontStyle style)
{
     block1.FontStyle = style;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM