强制启动DP的PropertyChangedCallback

时间:2013-09-02 12:40:16

标签: wpf mvvm dependency-properties change-notification

我的问题可能听起来有点类似 this question

当我的自定义UserControl的DependencyProperty发生更改时,我有一个通知栏经过某些动画。这里是代码实现:

    public string StatusBarText
    {
      get { return (string)GetValue(StatusBarTextProperty); }
      set { SetValue(StatusBarTextProperty, value); }
    }

   public static readonly DependencyProperty StatusBarTextProperty =
        DependencyProperty.Register("StatusBarText", typeof(string), typeof(WorkspaceFrame), new FrameworkPropertyMetadata(null, StatusBarTextChangedCallBack));

    private static void StatusBarTextChangedCallBack(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
      if (!string.IsNullOrWhiteSpace(Convert.ToString(e.NewValue)))
      {
        var workspaceFrame = d as WorkspaceFrame;
        if (null == workspaceFrame)
          return;
        var storyboard = workspaceFrame.FindResource("notificationBarAnimation") as Storyboard;
        if (null == storyboard)
          return;
        var statusBar = workspaceFrame.Template.FindName("PART_StatusBar", workspaceFrame) as Border;
        if (null == statusBar)
          return;
        //Run the animation
        storyboard.Begin(statusBar);
      }
    }

这里是动画的边框:

<Border x:Name="PART_StatusBar" Margin="5" BorderThickness="2" VerticalAlignment="Top"
                    DataContext="{Binding Path=StatusText}" Opacity="0"
                    Visibility="{Binding Path=Opacity, Mode=OneWay, RelativeSource={RelativeSource Self}, Converter={StaticResource doubleToVis}}"
                    BorderBrush="{StaticResource StatusMessageBackBrush}">

                <Border.Background>
                  <SolidColorBrush Color="{StaticResource StatusMessageBackColor}" Opacity="0.7"/>
                </Border.Background>

                <TextBlock Margin="10" FontSize="17" Foreground="{StaticResource BlackColorBrush}" Text="{Binding}">

                </TextBlock>
              </Border>

现在可能很清楚,此DP绑定到VM属性,该属性在设置时触发PropertyChangedNotification(INotifyProeprtyChanged)。 现在问题是只有在DP的旧值和新值发生一些变化时才会调用 StatusBarTextChangedCallBack 。有没有办法强迫它运行?如果没有,有什么办法吗? 我需要一遍又一遍地显示相同的通知。动画应该开始。

的问候,

詹姆斯

2 个答案:

答案 0 :(得分:1)

您可以注册CoerceValueCallBack函数而不是ValueChanged。像这样:

public static readonly DependencyProperty StatusBarTextProperty =
        DependencyProperty.Register("StatusBarText", typeof(string), typeof(WorkspaceFrame), new FrameworkPropertyMetadata(null,null, StatusBarTextCoerceValueCallBack));



private static object StatusBarTextCoerceValueCallBack(DependencyObject d, object value)
{

 }

即使值相同,当属性值发生更改时,也会始终触发CoerceValueCallback。

由于

答案 1 :(得分:1)

实现所需(或手动调用事件处理程序)的常规方法是创建一个启动动画的方法。然后从属性内部调用该动画启动方法更改处理程序。这样,您可以随时调用此方法。