本文介绍了如何在 Silverlight 中创建类似 WPF 的数据触发器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How might i create a trigger for a Silverlight datagrid in which the cell background color changes based on the cell value?I worked on a WPF project sometime ago and I recall this was quite simple via DataTriggers in the xaml. However this functionality doesn't appear to be available in Silverlight and i'm stuck as to where to start.

谢谢大家.

推荐答案

首先,Silverlight 中触发器的替代品是 VisualStateManager.VSM 实际上比触发器强大得多,因为它允许您在状态更改时执行 StoryBoard.

Firstly, the replacement for triggers in Silverlight is the VisualStateManager. The VSM is actually much more powerful than triggers as it allows you to execute a StoryBoard when the state changes.

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

If you don't need animation in your situation, the way I'd solve it would be using an IValueConverter. Create a Border in the DataTemplate, and bind the background brush to your DataItem's property that you want use to change the background brush.

    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 将如下所示:

Then, your XAML would look something like this:

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

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

If you DO need animation, then you're going to want to read up on the VisualStateManager. Essentialy what you'd do is create a Templated or UserControl with a dependency property, then when that property changes determine what state the control should be in, and invoke the visual state manager. The syntax is something like

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

这篇关于如何在 Silverlight 中创建类似 WPF 的数据触发器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 06:26