开发者

Set row properties for a data bound datagrid

开发者 https://www.devze.com 2023-01-29 11:57 出处:网络
I have a DataGrid bound to a object (using MVVM pattern). <DataGrid ItemsSource=\"{Binding Path=RecordSet}\"

I have a DataGrid bound to a object (using MVVM pattern).

<DataGrid ItemsSource="{Binding Path=RecordSet}"
          AutoGenerateColumns="False"
          IsReadOnly="True"
          Name="ResultGrid">
    <DataGrid.Columns>
        <DataGridTextColumn Header="ID" Binding="{Binding Path=Id开发者_开发百科}" Width="Auto"/>
        <DataGridTextColumn Header="Foo" Binding="{Binding Path=Foo}" Width="*"/>
    </DataGrid.Columns>
</DataGrid>

Here:

RecordSet is a List<Record>.

This works fine. The data loads up fine and everything. I wanted to know if there was away for me to set some properties on individual rows i.e. bound a row property to a value in my ViewModel (set each row's Row.IsEnable based on the Record.Enable) I am a newbie at WPF.

Thanks


This should work. Put this style inside your DataGrid.

<DataGrid.RowStyle>                
            <Style TargetType="DataGridRow">       
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=Enabled}"  Value="false">
                        <Setter Property="Visibility" Value="Hidden"/>
                        <Setter Property="Height" Value="0"/>
                    </DataTrigger>                        
                </Style.Triggers>
            </Style>
        </DataGrid.RowStyle>

This will make a row invisble and have no height if the record bound this row is not enabled. The Enabled property in the "{Binding Path=Enabled}" belongs to your Record. I don't know if you have that already, but you'll need something like it.


To follow up on wangburger's answer.
To bind the IsEnabled Property for each DataGridRow to Enabled in Record you can do this

<DataGrid ItemsSource="{Binding Path=RecordSet}" 
          AutoGenerateColumns="False" 
          IsReadOnly="True" 
          Name="ResultGrid"> 
    <DataGrid.Resources>
        <Style TargetType="DataGridRow">
            <Setter Property="IsEnabled" Value="{Binding Enabled}"/>
        </Style>
    </DataGrid.Resources>
    <DataGrid.Columns> 
        <DataGridTextColumn Header="ID" Binding="{Binding Path=Id}" Width="Auto"/> 
        <DataGridTextColumn Header="Foo" Binding="{Binding Path=Foo}" Width="*"/> 
    </DataGrid.Columns> 
</DataGrid> 


Note: if you set a row style to IsEnabled=false then that row cannot actually be selected at all, neither will the cursor keys skip over it. This may or may not be what you want.

if you want specifically to set IsEnabled=false (and I realize you just gave that as an example), but still allow the row to be selectable then you'll need (AFAIK) to set IsEnabled=false for each column template.

0

精彩评论

暂无评论...
验证码 换一张
取 消