首页 文章

C#WPF DataGrid将行背景绑定到DataRow中的Property

提问于
浏览
0

我需要将DataRow的背景绑定到附加到DataRow的对象的属性 . 我所做的是:

  • 我扩展了DataRow类,使其具有[object]类型的'Tag'属性 .

例:

myDataTable.Rows.Cast<ExtendedDataRow>().ToList(){r => {
    r.Tag = Brushes.Green;
});

所以基本上对于每一行,都有一个Tag属性,它是一个Brush,Green . 我需要将我的DataTable绑定到此数据集,并将每一行绑定到Tag属性 .

我尝试过的:

<DataGrid ItemsSource="{Binding myDataTable}">
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="Background" Value="{Binding Tag.Background}" />
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

但是当我尝试绑定它时,它似乎没有“拾取”Tag项 . 我需要为此创建一个ItemTemplate吗? (我试过了,也没用)

Note :数据集已成功绑定,在ViewModel的代码中,我可以看到每行的Tag项已填充 .

提前致谢

EDIT :已要求查看我的ExtendedDataRow类是如何使用的:

public class ExtendedDataTable : DataTable {
    public ExtendedDataTable()
        : base() {
    }

    public ExtendedDataTable(string tableName)
        : base(tableName) {
    }

    public ExtendedDataTable(string tableName, string tableNamespace)
        : base(tableName, tableNamespace) {
    }

    // Return the RowType as ExtendedDataRow instead of DataRow
    protected override Type GetRowType() {
        return typeof(ExtendedDataRow);
    }

    // Use the RowBuilder to return an ExtendedDataRow instead of DataRow
    protected override DataRow NewRowFromBuilder(DataRowBuilder builder) {
        return new ExtendedDataRow(builder);
    }
}

public class ExtendedDataRow : DataRow {
    public ExtendedDataRow()
        : base(null) {
    }

    public ExtendedDataRow(DataRowBuilder rb)
        : base(rb) {
    }

    // The tag object attached to the ExtendedDataRow
    public object Tag { get; set; }
}

Edit 2 :要绑定到ExtendedDataTable而不是普通的DataTable,您必须填充普通的DataTable,并使用其IDataReader填充ExtendedDataTable的数据集:

myDt = new ExtendedDataTable();
dt = new DataTable();
var dt = GetDataTable("SELECT * FROM SomeTable");
var reader = dt.DataSet.CreateDataReader(dt);
myDt.Load(reader);

1 回答

  • 1

    我按照预期做了所有事情,就像你做的那样 .

    我通过查看输出窗口注意到了这个问题:

    System.Windows.Data Error: 40 : BindingExpression path error: 'Tag' property not found on 'object' ''DataRowView' (HashCode=30296746)'. BindingExpression:Path=Tag; DataItem='DataRowView' (HashCode=30296746); target element is 'DataGridRow' (Name=''); target property is 'Background' (type 'Brush')
    

    DataRow是一些内部包含称为DataRowView的东西

    快速浏览msdn - DataRowView.Row

    XAML:

    <DataGrid CanUserAddRows="False" ItemsSource="{Binding Table}">                     
            <DataGrid.RowStyle>
                <Style TargetType="DataGridRow">
                    <Setter Property="Background" Value="{Binding Row.Tag, Mode=OneWay}" />
                </Style>
            </DataGrid.RowStyle>
        </DataGrid>
    

相关问题