简体   繁体   中英

WPF Checkbox.Checked event is firing before datagrid is loaded

I have a datagrid with 3 columns on my window. Columns are IsChecked, Id, Name.

<DataGrid AutoGenerateColumns="False" CanUserAddRows="False" SelectionMode="Single" CanUserDeleteRows="False" x:Name="dg" x:FieldModifier="public">
    <DataGrid.CellStyle>
        <Style TargetType="DataGridCell">
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
            <Setter Property="Height" Value="22"/>
        </Style>
    </DataGrid.CellStyle>
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="" IsReadOnly="True" CanUserSort="False">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <CheckBox IsChecked="{Binding IsChecked}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
            <DataGridTemplateColumn.CellStyle>
                <Style TargetType="DataGridCell">
                    <EventSetter Event="CheckBox.Checked" Handler="CheckBox_Checked"/>
                    <EventSetter Event="CheckBox.Unchecked" Handler="CheckBox_Unchecked"/>
                </Style>
            </DataGridTemplateColumn.CellStyle>
        </DataGridTemplateColumn>
        <DataGridTextColumn MinWidth="60" Header="ID" Binding="{Binding Id}" IsReadOnly="True" CanUserSort="False"></DataGridTextColumn>
        <DataGridTextColumn MinWidth="80" Header="Name" Binding="{Binding Name}" IsReadOnly="True" CanUserSort="False"></DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

There are 2 events that I am setting to this checkbox. But when I open the window, these events are firing before my window is fully loaded and datagrid is shown.

How can I prevent this? Or is there another way to set these events?

Don't use the EventSetter in the xaml. Create event handlers like this:

   <CheckBox
        Content="CheckBox"
        Checked="CheckBox_Checked"
        Unchecked="CheckBox_Unchecked"/>
    private void CheckBox_Checked(object sender, RoutedEventArgs e)
    {
        Handle(sender as CheckBox);
    }

    private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
    {
        Handle(sender as CheckBox);
    }

    void Handle(CheckBox checkBox)
    {
       bool checked = checkBox.IsChecked.Value;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM