【问题标题】:Changing text in textblock to italicized on MouseEnter在 MouseEnter 上将文本块中的文本更改为斜体
【发布时间】:2016-11-29 05:25:32
【问题描述】:

我有一个包含一些非斜体文本的文本块。当鼠标进入文本块时,文本通过使用后面的代码而改变。我希望后面的代码也能够将文本更改为斜体。这是我到目前为止所拥有的:

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"/>

代码隐藏(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";
    }
}

我已经研究过使用 System.Drawing 和 FontStyle.Italic;虽然我没有成功地让它发挥作用。

【问题讨论】:

  • 你真的应该为此使用样式和触发器。

标签: c# wpf xaml system.drawing


【解决方案1】:

这就是 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">
            <TextBlock.Style>
            <Style TargetType="TextBlock">
                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="FontStyle" Value="Italic" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
        </TextBlock>

但是,如果您真的愿意,这里有一个示例,说明您可以如何从代码隐藏中实现该功能。

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;
}

【讨论】:

  • 感谢您的回复!我知道在这种情况下使用背后的代码是不好的做法。我很想知道是否有办法在不使用样式和触发器(严格代码后面)的情况下实现这一点。
  • 谢谢伙计!完美运行!
  • 随时。您可能需要点击答案评分下的“检查”符号以验证此问题是否已解决。编码愉快!
  • 这里不需要DataTriggerIsMouseOver 上的Trigger 应该可以工作。
  • 谢谢。我脑子里有MVVM。我的答案已更新。
猜你喜欢
  • 1970-01-01
  • 2010-09-24
  • 2021-08-23
  • 2018-10-21
  • 1970-01-01
  • 2013-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多