【问题标题】:How to bind DataGrid cell text FontWeight to some property in the DataTable cell the grid is binded to?如何将 DataGrid 单元格文本 FontWeight 绑定到网格绑定到的 DataTable 单元格中的某个属性?
【发布时间】:2021-10-23 16:24:19
【问题描述】:

我已经尝试过这样做,但它并没有像我预期的那样工作。我将某个类的对象放置到(该类型的)表列之一,如果 bool 属性“bold”设置为“true”,则尝试使文本变为粗体。

一些“项目类”:

public class CellItem {
    public string str { get; set; }
    public bool bold { get; set; }

    public CellItem (string txt, bool bld) {
        str = txt;
        bold = bld;
    }
    public override string ToString() {
        return str;
    }
}

在某些数据上下文中:

DataTable _grid_items = new DataTable("table");
public DataView grid_items { get => _grid_items.DefaultView; }
...
_grid_items.Columns.Add(new DataColumn($"column {colnum++}", typeof (CellItem));
_grid_items.Columns.Add(new DataColumn("column 1"));
_grid_items.Rows.Add(new CellItem("row 0 col 0", false), "row 0 col 1");
_grid_items.Rows.Add(new CellItem("row 1 col 0", true), "row 1 col 1");
_grid_items.Rows.Add(new CellItem ("row 2 col 0", true), "row 2 col 1");
...

在 XAML 中:

   <DataGrid ItemsSource="{Binding grid_items}" GridLinesVisibility="All" 
                          CanUserAddRows="False" HorizontalAlignment="Left" Height="200"
                          Margin="0" VerticalAlignment="Top" Width="400">
            <DataGrid.CellStyle>
                <Style TargetType="DataGridCell">
                    <Setter Property="TextBlock.TextAlignment" Value="Center" />
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding CellItem.bold}" Value="true">
                            <Setter Property="FontWeight" Value="Bold" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </DataGrid.CellStyle>
        </DataGrid>

问题是为什么文本“row 1 col 0”和“row 2 col 0”不是粗体,如何纠正?

【问题讨论】:

    标签: wpf datatable binding datagrid


    【解决方案1】:

    您不能绑定到DataTable 中的自定义对象的属性。

    DataTable 替换为IEnumerable&lt;CellItem&gt;

    List<CellItem> _grid_items = new List<CellItem>();
    public IEnumerable<CellItem> grid_items { get => _grid_items; }
    ...
    _grid_items.Add(new CellItem("row 0 col 0", true);
    ...
    

    ...并直接绑定到模板中的属性:

    <DataTrigger Binding="{Binding bold}" Value="true">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-27
      • 1970-01-01
      • 2011-07-31
      • 1970-01-01
      • 2017-03-06
      • 2013-08-18
      • 1970-01-01
      • 2020-10-02
      相关资源
      最近更新 更多