【问题标题】:Dynamic row background datagrid Silverlight动态行背景数据网格 Silverlight
【发布时间】:2012-04-25 01:12:00
【问题描述】:

我有一个绑定到 ItemsSource 的 DataGrid 控件。我的 ItemsSource 是一个 ObservableCollection,我总是插入我订购的物品。我需要根据 DataGrid 上的值及其索引来设置 DataGrid 每一行的背景。 你知道有什么办法吗? 注意:ObservableCollection 将被另一个线程更新,所以当它更新时,我必须更新网格的背景颜色。

我见过一些人使用转换器做类似的事情,但我所有的业务逻辑都在 ViewModel 中,我需要从中获取值以发现哪种颜色将成为背景。

提前致谢。

【问题讨论】:

    标签: silverlight datagrid background-color


    【解决方案1】:

    您可以将 LoadingRow 事件处理程序添加到您的 DataGrid,然后在其各自项目的视图模型属性上设置到每行的 Background 属性的绑定:

    XAML 数据网格:

    <data:DataGrid ItemsSource="{Binding FooBars}" LoadingRow="dataGrid_LoadingRow" >
        <data:DataGrid.Columns>
            <data:DataGridTextColumn Header="FOO" Binding="{Binding Foo}" Width="200" />
            <data:DataGridTextColumn Header="BAR" Binding="{Binding Bar}" Width="60"/>
        </data:DataGrid.Columns>
    </data:DataGrid>
    

    代码隐藏:

    private void packetsDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
    {
        Binding backgroundBinding = new Binding("FooBarItemBackground");
        backgroundBinding.Source = e.Row.DataContext;
        e.Row.SetBinding(DataGridRow.BackgroundProperty, backgroundBinding);
    }
    

    【讨论】:

    • 有一个问题...例如:当我添加新行时,我必须更新下面的每一行都必须更新其背景。
    • 没问题 :) 添加新行时,可能会触发视图模型上的事件以更新每个项目的背景颜色属性。由于它是数据绑定的,因此您不必重新绑定网格或任何东西。
    • 这听起来像我正在使用的方式也应该是要走的路
    猜你喜欢
    • 1970-01-01
    • 2011-01-24
    • 2011-01-11
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    • 2018-02-02
    • 2011-11-04
    • 2014-03-21
    相关资源
    最近更新 更多