shreesha
shreesha

Reputation: 1881

WPF:Using checkbox IsChecked property in DataTrigger

I am trying to use WPF checkbox's IsChecked property in a DataTrigger.Based on the value i am setting particular DataGridRow's background.

My NOT WORKING code

    <Style TargetType="{x:Type DataGridRow}">
                <Setter Property="Background" Value="LightGray" />
                <Setter Property="SnapsToDevicePixels" Value="true"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=chkbox, Path=IsChecked}" Value="true">
                        <Setter Property="Background" Value="LightCyan" />
                     </DataTrigger>
                </Style.Triggers>
            </Style>

<DataGrid x:Name="dataGrid1" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTemplateColumn MinWidth="40" Width="Auto" Header="Select">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <CheckBox  x:Name="chkbox" IsChecked="{Binding Selected, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"></CheckBox>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>

                    </DataGridTemplateColumn>

            </DataGrid.Columns>
  </DataGrid>

Then I checked this link and changed the code as below and it is working fine.Here Selected is my public property.

 <Style TargetType="{x:Type DataGridRow}">
                <Setter Property="Background" Value="LightGray" />
                <Setter Property="SnapsToDevicePixels" Value="true"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Selected}" Value="true">
                        <Setter Property="Background" Value="LightCyan" />
                      </DataTrigger>
                </Style.Triggers>
            </Style>

Please help me to understand why my original code is not working? am i missing anything.
google did not help.surprisingly there is no thread for this on SO also! Thank you for the help.

Upvotes: 1

Views: 1453

Answers (1)

David
David

Reputation: 10708

The original code is not working because you're trying to locate an object via ElementName which exists as a templated object, and thus isn't created until after the binding tries to resolve. Generally, you should only use ElementName when referring to ancestor objects in the visual tree, and not to children, particularly templated children.

As mentioned in comments, it would also not be possible to use a {RelativeSource FindAncestor... binding here because the CheckBox is a child, not an ancestor, of the DataGridRow

Upvotes: 3

Related Questions