【问题标题】:How to use DataTrigger from code in Silverlight?如何在 Silverlight 中使用代码中的 DataTrigger?
【发布时间】:2011-11-26 21:08:42
【问题描述】:

我找到了一些与 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 发出更改通知。

【问题讨论】:

  • 查看调试输出,看起来您的绑定不正确:'IsFocused'。也许双“s”在这里是个问题?
  • @invisible -- 谢谢,但这次不是这样 :)

标签: c# .net silverlight datatrigger


【解决方案1】:

尝试使用命名空间:

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;

【讨论】:

    【解决方案2】:

    最后我遗漏了两点:

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

    我不太明白为什么第二点是必要的,但似乎是。

    希望对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 2011-04-01
      • 2014-06-05
      • 2011-07-11
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-17
      相关资源
      最近更新 更多