【问题标题】:How to Apply Storyboard as Style如何将故事板应用为样式
【发布时间】:2020-05-10 18:51:02
【问题描述】:

我想将Storyboard 应用到我的Rectangle Fill,如下所示:

<Rectangle Name="MyRectangle"
  Width="100"
  Height="100">
  <Rectangle.Fill>
    <SolidColorBrush x:Name="MySolidColorBrush" Color="Blue" />
  </Rectangle.Fill>
  <Rectangle.Triggers>
    <EventTrigger RoutedEvent="Rectangle.MouseEnter">
      <BeginStoryboard>
        <Storyboard>
          <ColorAnimation 
            Storyboard.TargetName="MySolidColorBrush"
            Storyboard.TargetProperty="Color"
            From="Blue" To="Red" Duration="0:0:1" />  
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Rectangle.Triggers>
</Rectangle> 

但我想在Style 中插入Storyboard,我试过这个:

<Style xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:s="clr-namespace:System;assembly=mscorlib" 
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   TargetType="{x:Type Rectangle}">

<Style.Triggers>

    <EventTrigger RoutedEvent="Shape.Loaded">
        <BeginStoryboard>
            <Storyboard>
                <ColorAnimation 
            Storyboard.TargetName="MySolidColorBrush"
            Storyboard.TargetProperty="Color"
            From="Blue" To="Red" Duration="0:0:1" />
            </Storyboard>
        </BeginStoryboard>
    </EventTrigger>

</Style.Triggers>

<Setter Property="Shape.Fill" Value="Blue" x:Name="MySolidColorBrush"/>

</Style>

使用此代码:

var rect = new Rectangle();

using (FileStream stream = new FileStream("myStyle.xaml", FileMode.Open))
   rect.Style = XamlReader.Load(stream) as Style;

但它不起作用并引发异常。我必须如何改变我的风格?

【问题讨论】:

  • 您是否必须使用 XamlReader 和所有这些东西来制作简单的样式?我不确定,但我认为您创建样式的方式有点不常见。
  • @HichemC 我希望有可能使用外部资源设置样式,即我希望第 3 方可以选择样式,您有其他选择吗?
  • 您可以使用类库项目,在那里添加资源字典,然后将 dll 添加到您当前的项目中,这样您就可以通过 标签获取这些资源
  • @HichemC 不,这样我有许多预定义的样式,我不能添加更多

标签: c# wpf styles storyboard shapes


【解决方案1】:

在你的故事板中改变它

Storyboard.TargetProperty="Color" 

Storyboard.TargetProperty="Fill.Color"

并删除

Storyboard.TargetName="MySolidColorBrush"

【讨论】:

  • 您的回答很有帮助,因为我只需将 Storyboard.TargetProperty="Color" 更改为 Storyboard.TargetProperty="Fill.Color" 并删除 Storyboard.TargetName="MySolidColorBrush" 即可。编辑您的答案,我会标记为已接受。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-20
  • 2017-05-05
  • 2011-12-14
  • 2012-07-31
  • 1970-01-01
  • 2014-11-22
  • 2012-02-20
相关资源
最近更新 更多