如何从Silverlight中的代码中使用DataTrigger?

时间:2011-09-28 13:11:03

标签: c# .net silverlight datatrigger

我找到了一些与WPF相关的示例,但没有找到Silverlight。

那么,在代码中设置Microsoft.Expression.Interactivity.Core.DataTrigger的工作示例是什么?

这是我目前拥有的代码,虽然它不起作用(没有例外,但在运行时没有任何反应):

// Set up a storyboard
var duration = new Duration(TimeSpan.FromMilliseconds(400));
var animation = new ColorAnimation
{
    To = Colors.White,
    RepeatBehavior = RepeatBehavior.Forever,
    AutoReverse = true,
    Duration = duration
};
var sb = new Storyboard
{
    RepeatBehavior = RepeatBehavior.Forever, 
    AutoReverse = true, 
    Duration = duration
};
sb.Children.Add(animation);
Storyboard.SetTarget(animation, fillBrush);
Storyboard.SetTargetProperty(animation, new PropertyPath("(SolidColorBrush.Color)"));

// Configure the data trigger
var focusTrigger = new DataTrigger
{
    Binding = new Binding("IsFocussed")
    {
        Source = asset,
        Mode = BindingMode.OneWay
    }, 
    Value = true
};
focusTrigger.Actions.Add(new ControlStoryboardAction
{
    Storyboard = sb, 
    ControlStoryboardOption = ControlStoryboardOption.Play, 
    IsEnabled = true
});

asset.IsFocussed通过INotifyPropertyChanged更改并提出更改通知。

2 个答案:

答案 0 :(得分:0)

尝试使用命名空间:

System.Windows.Interactivity

并在“配置数据触发器”注释

后添加以下内容
// Configure the data trigger

// Configure the TriggerCollection
TriggerCollection triggers = Interaction.GetTriggers(fillBrush);
var focussedTrigger = new EventTrigger("GotFocus");
focussedTrigger.Actions.Add(
            new ControlStoryboardAction{Storyboard = sbFocussed});

var unfocussedTrigger = new EventTrigger("LostFocus");
unfocussedTrigger.Actions.Add(
            new ControlStoryboardAction { Storyboard = sbUnfocussed });

triggers.Add(focussedTrigger);
triggers.Add(unfocussedTrigger);

请注意:

using EventTrigger = System.Windows.Interactivity.EventTrigger;
using TriggerCollection = System.Windows.Interactivity.TriggerCollection;

答案 1 :(得分:0)

最后我错过了两位:

  1. 将触发器添加到画笔:

    var triggers = Interaction.GetTriggers(fillBrush);
    triggers.Add(focusTrigger);
    
  2. 使用BindingOperators.SetBinding设置触发器的绑定,而不是Binding属性设置器:

    var binding = new Binding("IsFocussed") { Source = asset, Mode = BindingMode.OneWay };
    BindingOperations.SetBinding(focusTrigger, PropertyChangedTrigger.BindingProperty, binding);
    
  3. 我不明白为什么第二点是必要的,但似乎是。

    希望能帮助其他人。