开发者

How to use DataTrigger from code in Silverlight?

I have found a few examples that relate to WPF, but none for Silverlight.

So, what is a working example of setting up a Microsoft.Expression.Interactivity.Core.DataTrigger in code?

Here is the code I currently have, though it doesn't work (no exceptions, but nothing happens at runtime):

// Set up a storyboard
var duration = new Duration(Tim开发者_JS百科eSpan.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 changes and raises change notifications via INotifyPropertyChanged.


Try using the namespace:

System.Windows.Interactivity

and add the following after your "Configure the data trigger" comment

// 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);

note:

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


In the end I was missing two bits:

  1. Add the trigger to the brush:

    var triggers = Interaction.GetTriggers(fillBrush);
    triggers.Add(focusTrigger);
    
  2. Set the binding on the trigger using BindingOperators.SetBinding, not the Binding property setter:

    var binding = new Binding("IsFocussed") { Source = asset, Mode = BindingMode.OneWay };
    BindingOperations.SetBinding(focusTrigger, PropertyChangedTrigger.BindingProperty, binding);
    

I can't quite see why the second point was necessary, but it seemed to be.

Hope that helps someone else out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜