【问题标题】:How to change background colour depending on binding value on Windows RT如何根据 Windows RT 上的绑定值更改背景颜色
【发布时间】:2012-12-04 12:03:30
【问题描述】:

如何使用 Windows RT / Windows 应用商店应用程序中的 <ListView> 控件在 Excel 中实现下面看到的这种效果(假设我有一个整数列表用作我的 ItemsSource) .

本质上,我想知道根据每个数据绑定值所持有的内容,直接应用样式或设置背景颜色的最有效方法。

我们真的需要something like this。但 Windows RT 应用似乎不支持数据触发器。

【问题讨论】:

    标签: .net xaml windows-runtime winrt-xaml


    【解决方案1】:

    在您的ItemTemplete 创建矩形,然后使用下面的ValueConverter 将其Fill 属性绑定到您的列表元素

    public sealed class IntegerToColorBrushConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            switch ((int)value)
            {
                case 5:
                    return new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Colors.Green);
                case 10:
                    return new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Colors.Yellow);
                case 15:
                    return new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Colors.Orange);
                case 25:
                    return new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Colors.Red);
                case 0:
                    return new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Colors.DarkGreen);
                default:
                    return new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Colors.Transparent);
            }
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
    

    XAML:

        <ResourceDictionary>
            <local:IntegerToColorBrushConverter x:Key="IntegerToColorBrushConverter"/>
            <DataTemplate x:Key="DataTemplate1">
                <Grid>
                    <Rectangle Fill="{Binding Converter={StaticResource IntegerToColorBrushConverter}, Mode=OneWay}" />
                </Grid>
            </DataTemplate>
        </ResourceDictionary>
    
        <ListView ItemsSource="{Binding Elements}" ItemTemplate="{StaticResource DataTemplate1}"/>
    

    【讨论】:

    • 我今天测试一下,非常感谢。这很好,并且将允许最大的灵活性..但是诉诸编程方法是唯一的方法吗?我更喜欢可以避免重新编译的东西。
    • 好吧,我并不是要讽刺,但是您必须编写一些代码才能以这种方式发生,否则其他编程方法是唯一的方法 :) 但说真的,我不知道任何其他方法。
    • 好吧,让我换个说法,只是声明式的;意思是避免编译。我不太喜欢根据 C# 代码指定我的视图的外观。在我看来,我的视图/UI 应该全心全意地在 XAML 中声明。
    • 我会接受这个答案,除非我听到更符合我所说的内容
    猜你喜欢
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多