如何更改Silverlight DataGridRow的背景颜色?

时间:2011-02-09 13:37:22

标签: silverlight-4.0 datagrid binding background row

我有一个Silverlight DataGrid绑定到MyObjects的集合。 MyObject有一个名为IsHighlighted的布尔字段。 我想在此值为true时更改行的背景颜色。并且如果变得虚假则将其改回。

我已经尝试使用Loading_Row事件(as explained here),但它对我不起作用,因为此事件只调用一次,而我的objetcs都将布尔值设置为此时为false(当另一个组件被选中时,它只会成为truc;这样,我检查了值)。

有人有线索吗?提前谢谢!

更新:我做了一个测试应用程序来说明,它重现了我的问题。

<navigation:Page x:Class="AViews.Tests" 
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
           xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
           xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
           xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"  
           mc:Ignorable="d"
           xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
           DataContext="{Binding RelativeSource={RelativeSource Self}}"
           d:DesignWidth="640" d:DesignHeight="480"
           Title="Tests Page">
    <Grid x:Name="LayoutRoot">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <sdk:DataGrid Grid.Row="0" ItemsSource="{Binding AllItems, Mode=TwoWay}" AutoGenerateColumns="False" LoadingRow="DataGrid_LoadingRow">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Binding="{Binding Value1}" Header="Value1" />
                <sdk:DataGridTextColumn Binding="{Binding Value2}" Header="Value2"/>
                <sdk:DataGridCheckBoxColumn Binding="{Binding IsHighlighted}" Header="Is Highlighted" />
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>

        <Button Content="Change !" Grid.Row="1" HorizontalAlignment="Left" Click="Button_Click" />

    </Grid>
</navigation:Page>

public partial class Tests : Page, INotifyPropertyChanged
{
    private SampleConverter bgConverter = new SampleConverter();
    Random r = new Random();

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = this.PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }

    private ObservableCollection<Sample> allItemsField = new ObservableCollection<Sample>();
    public ObservableCollection<Sample> AllItems
    {
        get
        {
            return this.allItemsField;
        }

        set
        {
            if (this.allItemsField != value)
            {
                this.allItemsField = value;
                this.OnPropertyChanged("AllItems");
            }
        }
    }

    public Tests()
    {
        InitializeComponent();
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        var tmp = Enumerable.Range(0, 100).Select(f => new Sample(f)).ToList();
        foreach (var item in tmp)
        {
            item.PropertyChanged += new PropertyChangedEventHandler(item_PropertyChanged);
        }

        var coll = new ObservableCollection<Sample>(tmp);

        this.AllItems = coll;
    }

    void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        this.OnPropertyChanged("AllItems");
    }

    private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
    {
        Binding b = new Binding("IsHighlighted")
        {
            Mode = BindingMode.OneWay,
            Converter = this.bgConverter,
            ValidatesOnExceptions = true
        };

        e.Row.SetBinding(DataGridRow.BackgroundProperty, b);
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        foreach (var item in this.AllItems)
        {
            item.IsHighlighted = r.Next(1000) % 2 == 0;
        }
    }
}

public class Sample: INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = this.PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }

    private string value1Field = string.Empty;
    public string Value1
    {
        get
        {
            return this.value1Field;
        }

        set
        {
            if (this.value1Field != value)
            {
                this.value1Field = value;
                this.OnPropertyChanged("Value1");
            }
        }
    }

    private string value2Field = string.Empty;
    public string Value2
    {
        get
        {
            return this.value2Field;
        }

        set
        {
            if (this.value2Field != value)
            {
                this.value2Field = value;
                this.OnPropertyChanged("Value2");
            }
        }
    }

    private bool isHighlightedField = false;
    public bool IsHighlighted
    {
        get
        {
            return this.isHighlightedField;
        }

        set
        {
            if (this.isHighlightedField != value)
            {
                this.isHighlightedField = value;
                this.OnPropertyChanged("IsHighlighted");
            }
        }
    }

    public Sample(int index)
    {
        this.Value1 = string.Format("Value1 #{0}", index);
        this.Value2 = string.Format("Value2 #{0}", index);
    }
}

public class SampleConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        bool val = (bool)value;
        SolidColorBrush ret = val ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.Green);
        return ret;
    }

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

结果可以在这些图片上看到:

当我第一次到达页面时。 Start

我单击按钮,将一些(随机)值设置为true。如您所见,绑定已更新,而不是UI。 enter image description here

我使用滚动条,走到最后,然后回来,哦!精彩!所有行都正确着色: - (

enter image description here

1 个答案:

答案 0 :(得分:2)

请参阅以下链接,通过更改DataGridRow的控制模板来解决问题 绑定Fill的{​​{1}}属性。您可以使用BackgroundRectangleboolConverter转换为IsHighlighted

Silverlight DataGrid row color binding