如何在Silverlight中创建类似WPF的数据触发器?

时间:2011-01-02 15:13:30

标签: silverlight xaml datatrigger

如何为Silverlight数据网格创建触发器,其中单元格背景颜色根据单元格值而变化? 我之前曾参与过一个WPF项目,我记得在xaml中通过DataTriggers非常简单。但是,这个功能似乎在Silverlight中不可用,而且我不知道从哪里开始。

谢谢大家。

2 个答案:

答案 0 :(得分:2)

首先,Silverlight中触发器的替换是VisualStateManager。 VSM实际上比触发器更强大,因为它允许您在状态发生变化时执行StoryBoard。

如果你在你的情况下不需要动画,我解决它的方法就是使用IValueConverter。在DataTemplate中创建一个Border,并将背景画笔绑定到您想要用来更改背景画笔的DataItem属性。

    public class BrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
       value.ToString() == "Red" ? new SolidColorBrush(Color.Red) : SolidColorBrush(Color.Blue);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedExcpetion();
    }
}

然后,你的XAML看起来像这样:

<Border Background={Binding InterestingProperty,Converter={StaticResource BrushConverter}} />

如果您需要动画,那么您将需要阅读VisualStateManager。实际上你要做的是创建一个带有依赖属性的Templated或UserControl,然后当该属性更改时确定控件应该处于什么状态,并调用可视状态管理器。语法类似于

VisualStateManager.GoToVisualState(yourControlInstance,"TheState",boolUseTransitions);

答案 1 :(得分:0)

这是使用true和false Brush

的示例
 public class BoolToBrushConverter:DependencyObject,IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
      if(value is bool && (bool)value)
      {
        return TrueBrush;
      }

  return FalseBrush;
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
  throw new NotImplementedException();
}



public Brush FalseBrush
{
  get { return (Brush)GetValue(FalseBrushProperty); }
  set { SetValue(FalseBrushProperty, value); }
}

// Using a DependencyProperty as the backing store for FalseBrush.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty FalseBrushProperty =
    DependencyProperty.Register("FalseBrush", typeof(Brush), typeof(BoolToBrushConverter), new PropertyMetadata(null));



public Brush TrueBrush
{
  get { return (Brush)GetValue(TrueBrushProperty); }
  set { SetValue(TrueBrushProperty, value); }
}

// Using a DependencyProperty as the backing store for TrueBrush.  This enables animation, styling, binding, etc...

public static readonly DependencyProperty TrueBrushProperty =
    DependencyProperty.Register("TrueBrush", typeof(Brush), typeof(BoolToBrushConverter), new PropertyMetadata(null));}

和XAML

<UserControl.Resources>
    <converter:BoolToBrushConverter x:Key="enabledToBrushConverter"
               TrueBrush="White" FalseBrush="Gray" />
</UserControl.Resources> 

<TextBlock  Foreground="{Binding Element.IsEnabled,
  Converter={StaticResource enabledToBrushConverter}, ElementName= your_Element}"  />