如何根据使用MVVM绑定的数据更改DataGrid的单元格?

时间:2011-11-22 22:47:20

标签: c# wpf xaml datagrid mvvm-light

我正在使用MVVM Light Toolkit,我有一个绑定到ObservableCollection的DataGrid。只显示一个文本列。我希望单元格的文本为Bold或Normal,具体取决于显示的对象内部的布尔值。我想我可以使用RelayCommands,但它们只需要1个参数,我需要至少2个来获取CellContent(DataGridRowEventArgs和DataGrid本身)。我试图在“LoadingRow”事件上触发一个RelayCommand执行委托但只有一个参数我无法做到。

这是XAML中的DataGrid:

<DataGrid x:Name="dataGrid1" HorizontalAlignment="Left" Margin="112,34,0,8" Width="100" IsReadOnly="True" CanUserReorderColumns="False" CanUserResizeColumns="False" CanUserSortColumns="False" CanUserResizeRows="False" ItemsSource="{Binding CurrentNewsList}" AutoGenerateColumns="False" SelectedIndex="0">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Title}" MinWidth="92" Width="Auto" FontFamily="Segoe UI" Foreground="Black" FontWeight="{Binding CurrentNewsList[0].MyFont}"/>
        </DataGrid.Columns>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectionChanged">
                <Custom:EventToCommand Command="{Binding NewsSelectedCommand}" CommandParameter="{Binding SelectedIndex, ElementName=dataGrid1}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </DataGrid>

我在Blend中设置了网格。请注意,FontWeight的绑定类似于“{Binding CurrentNewsList [0] .MyFont}”。这样对吗 ?我也试过“{Binding MyFont}”,但两者都得到了相同的结果:没有BOld :(

MyFont在Object构造函数中设置了一个布尔值:

MyFont = newIsRead ? FontWeights.Normal : FontWeights.Bold;

请帮忙。

THX

3 个答案:

答案 0 :(得分:4)

您可以使用隐式样式和触发器:

<DataGrid.Resources>
    <Style TargetType="DataGridCell">
        <Style.Triggers>
            <DataTrigger Binding="{Binding MyBoolean}" Value="True">
                <Setter Property="TextElement.FontWeight" Value="Bold" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</DataGrid.Resources>

(如果您有更多列,则可以使用列上的样式(ElementStyle&amp; ElementEditingStyle)来限制效果)

答案 1 :(得分:1)

在这种情况下,我通常会创建一个专门用于绑定的“模型对象”。因此,不是绑定到可观察的“Customer”集合,而是绑定到可观察的“CustomerModel”集合,其中模型对象具有“CustomerName”属性,然后是与所需字体对应的其他属性(实际为如果您不希望VM层知道视图关注点,则可以通过值转换器解析字体对象或某种枚举。这个模型对象可以根据你提到的布尔属性找出可用的内容。

答案 2 :(得分:1)

以下是我设法使用H.B解决方案的方法:

            <DataGrid.Resources>
            <Style x:Key="Style1" TargetType="{x:Type TextBlock}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsRead}" Value="False">
                        <Setter Property="FontWeight" Value="Bold" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </DataGrid.Resources>
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Title}" ElementStyle="{StaticResource ResourceKey=Style1}" />
        </DataGrid.Columns>
相关问题