2015-04-21 3 views
0

Я хочу создать пользовательскую кнопку со стилем.Невозможно изменить непрозрачность на экземпляре неизменяемого объекта

<Grid> 
<Button x:Name="btnRun" Style="{StaticResource ButtonStyle}" Content="Run" 
Click="btn_Run" /> 
</Grid> 

Стиль имеет анимацию в зависимости от положения мыши. Анимация должна изменить непрозрачность DropShadowEffect. Но это не работает. Во время выполнения, когда пользователь при наведении мыши на кнопку программы кидает исключение:

Не может анимировать Непрозрачность на неизменном экземпляре объекта

Есть ли решение этой проблемы?

<Window.Resources> 
    <DropShadowEffect x:Key="dropShadow" x:Name="dropName" Color="red" ShadowDepth="0" BlurRadius="42" Direction="10" /> 
<Style x:Key="ButtonStyle" TargetType="{x:Type Button}"> 
     <Setter Property="Effect" Value="{StaticResource dropShadow}" /> 
     <Setter Property="Background" Value="Red"/> 
     <Setter Property="HorizontalAlignment" Value="Center"/> 
     <Setter Property="VerticalContentAlignment" Value="Center"/> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="{x:Type Button}"> 
        <ControlTemplate.Resources> 

         <Storyboard x:Key="myStoryboard"> 
          <DoubleAnimationUsingKeyFrames 
               Storyboard.Target= "{StaticResource ResourceKey=dropShadow}" 
               Storyboard.TargetProperty="Opacity" 
               Duration="0:0:1.6" 
               RepeatBehavior="Forever"> 
           <LinearDoubleKeyFrame KeyTime="0:0:0" Value="0"/> 
           <LinearDoubleKeyFrame KeyTime="0:0:0.8" Value="1"/> 
           <LinearDoubleKeyFrame KeyTime="0:0:1.6" Value="0"/> 
          </DoubleAnimationUsingKeyFrames> 
         </Storyboard>        
        </ControlTemplate.Resources> 
        <Grid> 
         <Path Fill="{TemplateBinding Background}" 
         Data="M 241,200 
      A 20,20 0 0 0 200,240 
      C 210,250 240,270 240,270 
      C 240,270 260,260 280,240 
      A 20,20 0 0 0 239,200" Margin="0,0,0,-15" Stretch="Fill" /> 
         <ContentPresenter VerticalAlignment="{TemplateBinding VerticalContentAlignment}" 
             HorizontalAlignment="{TemplateBinding HorizontalAlignment}"/> 
        </Grid> 
        <ControlTemplate.Triggers> 
         <Trigger Property="IsMouseOver" Value="True"> 
          <Trigger.EnterActions> 
           <BeginStoryboard Storyboard="{StaticResource myStoryboard}" /> 
          </Trigger.EnterActions> 
          <Trigger Property="IsMouseOver" Value="False">         
         </Trigger>        
        </ControlTemplate.Triggers> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter>    
    </Style> 
</Window.Resources> 
+0

Вы оживляющий ** Статическая ** Ресурс, который по умолчанию является общим для всех потребителей. Попробуйте добавить тень непосредственно в шаблон управления и оживить это. –

+0

Я попытался добавить DropShadowEffect в ControlTemplate.Resources, но у меня все еще та же проблема – SwitchOn

+0

ОК, уволил его в Visual Studio и получил его работу, проверьте мой правильный ответ, размещенный ниже. Nice heart btw ... не ожидал этого;) –

ответ

0

Вы не можете анимировать StaticResource, поэтому ключ должен указать DropShadowEffect в ControlTemplate, а затем вы можете ссылаться, что в раскадровке/DoubleAnimationUsingKeyFrames:

<Window x:Class="WpfApplication1.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Window.Resources> 

     <Style x:Key="ButtonStyle" TargetType="{x:Type Button}"> 
      <Setter Property="Background" Value="Red"/> 
      <Setter Property="HorizontalAlignment" Value="Center"/> 
      <Setter Property="VerticalContentAlignment" Value="Center"/> 
      <Setter Property="Template"> 
       <Setter.Value> 
        <ControlTemplate TargetType="{x:Type Button}"> 
         <ControlTemplate.Resources> 
          <Storyboard x:Key="myStoryboard"> 
           <DoubleAnimationUsingKeyFrames 
               Storyboard.TargetName= "dropName" 
               Storyboard.TargetProperty="Opacity" 
               Duration="0:0:1.6" 
               RepeatBehavior="Forever"> 
            <LinearDoubleKeyFrame KeyTime="0:0:0" Value="0"/> 
            <LinearDoubleKeyFrame KeyTime="0:0:0.8" Value="1"/> 
            <LinearDoubleKeyFrame KeyTime="0:0:1.6" Value="0"/> 
           </DoubleAnimationUsingKeyFrames> 
          </Storyboard> 
         </ControlTemplate.Resources> 
         <Grid> 
          <Grid.Effect> 
           <DropShadowEffect x:Name="dropName" Color="red" ShadowDepth="0" BlurRadius="42" Direction="10" />           
          </Grid.Effect> 
          <Path Fill="{TemplateBinding Background}" 
         Data="M 241,200 
      A 20,20 0 0 0 200,240 
      C 210,250 240,270 240,270 
      C 240,270 260,260 280,240 
      A 20,20 0 0 0 239,200" Margin="0,0,0,-15" Stretch="Fill" /> 
          <ContentPresenter VerticalAlignment="{TemplateBinding VerticalContentAlignment}" 
             HorizontalAlignment="{TemplateBinding HorizontalAlignment}"/> 
         </Grid> 
         <ControlTemplate.Triggers> 
          <Trigger Property="IsMouseOver" Value="True"> 
           <Trigger.EnterActions> 
            <BeginStoryboard Name="BeginStoryboard" Storyboard="{StaticResource myStoryboard}" /> 
           </Trigger.EnterActions> 
           <Trigger.ExitActions> 
            <RemoveStoryboard BeginStoryboardName="BeginStoryboard" /> 
           </Trigger.ExitActions> 
          </Trigger> 
         </ControlTemplate.Triggers> 
        </ControlTemplate> 
       </Setter.Value> 
      </Setter> 
     </Style> 
    </Window.Resources> 
    <Grid> 
     <Button Style="{StaticResource ButtonStyle}" Content="Run" /> 
    </Grid> 
</Window> 
+0

Спасибо, это решение работает отлично! – SwitchOn

+2

Плохой ответ. Постарайтесь объяснить, в чем проблема, и как вы это исправили? – Sinatr

Смежные вопросы