1. 程式人生 > >WPF Datagrid對滑鼠單擊進行響應,藉助EventSetter

WPF Datagrid對滑鼠單擊進行響應,藉助EventSetter

在做的一個c#的專案中發現Datagrid沒辦法直接對滑鼠單擊進行響應,

呼叫MouseDown事件也需要點選某一行第二次才能響應。

所以藉助EventSetter來簡單的實現了一個。

介面部分的程式碼

        <DataGrid x:Name="dataGrid" HorizontalAlignment="Left" Margin="10,38,0,0"
                  VerticalAlignment="Top" Height="257" FontSize="13.333"
                  AutoGenerateColumns
="False" AlternationCount="2" CanUserAddRows="False" MinWidth="504" Width="513" SelectionUnit="FullRow">
<DataGrid.RowStyle> <Style TargetType="DataGridRow"> <EventSetter Event="GotFocus" Handler="Item_GotFocus"/>
</Style> </DataGrid.RowStyle> <DataGrid.Columns> <DataGridCheckBoxColumn /> <DataGridTextColumn Header="歌曲名" Width="200" Binding="{Binding Path=Title}" IsReadOnly="True"/> <DataGridTextColumn Header
="藝術家" Width="127" Binding="{Binding Path=Artist}" IsReadOnly="True"/>
<DataGridTextColumn Header="專輯" Width="140" Binding="{Binding Path=Album}" IsReadOnly="True"/> </DataGrid.Columns> </DataGrid>

對應的c#的程式碼

        private void Item_GotFocus(object sender, RoutedEventArgs e)
        {
            var item = (DataGridRow)sender;
            FrameworkElement objElement = dataGrid.Columns[0].GetCellContent(item);
            if (objElement != null)
            {
                CheckBox objChk = (CheckBox)objElement;
                objChk.IsChecked = !objChk.IsChecked;
            }
        }

附上用mousedown事件的程式碼

        private void DataGrid_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                var se = dataGrid.SelectedItem;
                FrameworkElement objElement = dataGrid.Columns[0].GetCellContent(se);
                if (objElement != null)
                {
                    CheckBox objChk = (CheckBox)objElement;
                    objChk.IsChecked = !objChk.IsChecked;
                }
            }
        }

需要在這個介面的建構函式中新增

 dataGrid.MouseDown += DataGrid_MouseDown;