none
DataGrid, DataGridCheckBoxColumn. Нажал сработало событие, нажал ещё раз, снова сработало передав на текущий экземпляр класса ссылку. RRS feed

  • Общие обсуждения

  • Как это сделать? Есть DataGrid с галочками. Нужно поведение: Если не стоит ни одна галочка, то выводим подробности в другой DataGrid выделенной строки в первом DataGrid'e. Если стоит хотя бы одна галочка, то выводим подробности  для этой галочки. Кликнули поставив ещё галочку, сразу же обновились данные, не убирая фокус с ячейки кликнули сняв галочку, снова обновились данные. КАК??? Убил весь день, никак не получается сделать. Я подписался на события: CellEditEnding, PreparingCellForEdit, SelectionChanged. 

    Для того, чтобы данные в DG обновлялись сразу, я даже нагуглил такой пример:

            private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
            {
    
                DataGridCell cell = sender as DataGridCell;
                if (cell != null && !cell.IsEditing && !cell.IsReadOnly)
                {
                    if (!cell.IsFocused)
                    {
                        cell.Focus();
                    }
                    DataGrid dataGrid = FindVisualParent<DataGrid>(cell);
                    if (dataGrid != null)
                    {
                        if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow)
                        {
                            if (!cell.IsSelected)
                                cell.IsSelected = true;
                        }
                        else
                        {
                            DataGridRow row = FindVisualParent<DataGridRow>(cell);
                            if (row != null && !row.IsSelected)
                            {
                                row.IsSelected = true;
                            }
    
                        }
    
                    }
                }
            }
    
            static T FindVisualParent<T>(UIElement element) where T : UIElement
            {
                UIElement parent = element;
                while (parent != null)
                {
                    T correctlyTyped = parent as T;
                    if (correctlyTyped != null)
                    {
                        return correctlyTyped;
                    }
    
                    parent = VisualTreeHelper.GetParent(parent) as UIElement;
                }
    
                return null;
            }

    Вот код DataGrid'a:

    <Window x:Class="Wpf_DataGrid_CollectionView.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:command="http://www.galasoft.ch/mvvmlight"
            xmlns:converters="clr-namespace:Wpf_DataGrid_CollectionView.ViewModel.Cinema.Converters"
            xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
            Title="MainWindow"
            Width="525"
            Height="550"
            DataContext="{Binding Path=Main,
                                  Source={StaticResource Locator}}"
            WindowStartupLocation="CenterScreen">
    
      <Window.Resources>
        <converters:GenreToTextConverter x:Key="GenreToTextConverterKey" />
      </Window.Resources>
    
      <Grid>
        <Grid.RowDefinitions>
          <RowDefinition Height="70*" />
          <RowDefinition Height="449*" />
        </Grid.RowDefinitions>
    
    
        <!--
          <ListView ItemsSource="{Binding Persons}">
          <ListView.View>
          <GridView>
          <GridViewColumn Width="60"
          Header="Выбран">
          
          <GridViewColumn.CellTemplate>
          <DataTemplate>
          <CheckBox HorizontalAlignment="Stretch"
          VerticalAlignment="Stretch"
          Checked="ToggleButton_OnChecked"
          IsChecked="{Binding IsSelected}"
          Unchecked="ToggleButton_OnChecked">
        -->
        <!--
          <i:Interaction.Triggers>
          <i:EventTrigger EventName="Checked">
          <command:EventToCommand Command="{Binding NewItemSelectedCommand}"
          PassEventArgsToCommand="True" />
          
          </i:EventTrigger>
          </i:Interaction.Triggers>
        -->
        <!--
          </CheckBox>
          </DataTemplate>
          </GridViewColumn.CellTemplate>
          
          </GridViewColumn>
          <GridViewColumn Width="130"
          DisplayMemberBinding="{Binding Person.FirstName}"
          Header="Имя" />
          <GridViewColumn Width="130"
          DisplayMemberBinding="{Binding Person.LastName}"
          Header="Фамилия" />
          </GridView>
          </ListView.View>
          </ListView>
        -->
    
    
    
        <DataGrid x:Name="_personsDg"
                  Margin="3,3,3,0"
                  AutoGenerateColumns="False"
                  HorizontalGridLinesBrush="#FFB2B2B2"
                  ItemsSource="{Binding Persons}"
                  SelectedItem="{Binding SelectedItem,
                                         Mode=OneWayToSource}"
                  SelectionMode="Single"
                  SelectionUnit="FullRow"
                  VerticalGridLinesBrush="#FFB2B2B2">
    
          <DataGrid.CellStyle>
            <Style TargetType="{x:Type DataGridCell}">
              <EventSetter Event="PreviewMouseLeftButtonDown"
                           Handler="DataGridCell_PreviewMouseLeftButtonDown" />
            </Style>
          </DataGrid.CellStyle>
          <!--  CellEditEnding RowEditEnding  -->
          <i:Interaction.Triggers>
    
            <i:EventTrigger EventName="CellEditEnding">
              <command:EventToCommand Command="{Binding NewItemSelectedCommand}"
                                      PassEventArgsToCommand="True" />
            </i:EventTrigger>
    
            <i:EventTrigger EventName="PreparingCellForEdit">
              <command:EventToCommand Command="{Binding NewItemSelectedCommand}"
                                      PassEventArgsToCommand="True" />
            </i:EventTrigger>
    
            <i:EventTrigger EventName="SelectionChanged">
              <command:EventToCommand Command="{Binding SelectionChangedCommand}"
                                      PassEventArgsToCommand="True" />
            </i:EventTrigger>
    
          </i:Interaction.Triggers>
    
          <DataGrid.Columns>
    
    
            <DataGridTemplateColumn x:Name="PropertiesUpdateIndicatorColumn"
                                    Header="Выбран">
    
              <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                  <CheckBox IsChecked="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}" />
                </DataTemplate>
              </DataGridTemplateColumn.CellTemplate>
    
              <DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                  <CheckBox IsChecked="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}"  >
                    <CheckBox.Triggers>
                      <EventTrigger RoutedEvent="CheckBox.Checked">
                         
                      </EventTrigger>
                    </CheckBox.Triggers>
                  </CheckBox>
                </DataTemplate>
    
              </DataGridTemplateColumn.CellEditingTemplate>
    
            </DataGridTemplateColumn>
    
    
            <!--
              <DataGridCheckBoxColumn Binding="{Binding IsSelected,
              UpdateSourceTrigger=PropertyChanged}"
              
              ClipboardContentBinding="{x:Null}"
              Header="Выбран" />
            -->
    
    
            <DataGridTextColumn Binding="{Binding Person.FirstName}"
                                ClipboardContentBinding="{x:Null}"
                                Header="Имя"
                                IsReadOnly="True" />
    
            <DataGridTextColumn Binding="{Binding Person.LastName}"
                                ClipboardContentBinding="{x:Null}"
                                Header="Фамилия"
                                IsReadOnly="True" />
          </DataGrid.Columns>
    
        </DataGrid>
    
    
    
        <DataGrid Grid.Row="1"
                  Margin="3,3,3,0"
                  AutoGenerateColumns="False"
                  CanUserAddRows="False"
                  ItemsSource="{Binding Films}">
    
          <DataGrid.Columns>
    
            <DataGridTextColumn Binding="{Binding Title}"
                                ClipboardContentBinding="{x:Null}"
                                Header="Название"
                                IsReadOnly="True" />
    
            <DataGridTextColumn Binding="{Binding Genre,
                                                  Converter={StaticResource GenreToTextConverterKey}}"
                                ClipboardContentBinding="{x:Null}"
                                Header="Жанр"
                                IsReadOnly="True" />
          </DataGrid.Columns>
    
          <DataGrid.GroupStyle>
    
            <GroupStyle>
              <GroupStyle.ContainerStyle>
                <Style TargetType="{x:Type GroupItem}">
                  <Setter Property="Margin" Value="0,0,0,5" />
                  <Setter Property="Template">
                    <Setter.Value>
                      <ControlTemplate TargetType="{x:Type GroupItem}">
                        <Expander Background="#FF495B93"
                                  BorderBrush="#FF003C97"
                                  BorderThickness="1,1,1,5"
                                  IsExpanded="True">
                          <Expander.Header>
                            <DockPanel>
                              <TextBlock Width="100"
                                         Margin="5,0,0,0"
                                         FontWeight="Bold"
                                         Foreground="WhiteSmoke"
                                         Text="{Binding Path=Name}" />
    
                              <TextBlock FontWeight="Bold"
                                         Foreground="WhiteSmoke"
                                         Text="{Binding Path=ItemCount}" />
    
                            </DockPanel>
                          </Expander.Header>
                          <Expander.Content>
                            <ItemsPresenter />
                          </Expander.Content>
                        </Expander>
                      </ControlTemplate>
                    </Setter.Value>
                  </Setter>
                </Style>
              </GroupStyle.ContainerStyle>
            </GroupStyle>
    
            <!--  Style for groups at top level.  -->
            <GroupStyle>
              <GroupStyle.ContainerStyle>
                <Style TargetType="{x:Type GroupItem}">
                  <Setter Property="Margin" Value="0,0,0,5" />
                  <Setter Property="Template">
                    <Setter.Value>
                      <ControlTemplate TargetType="{x:Type GroupItem}">
                        <Expander Background="#FFAFB8D4"
                                  BorderBrush="#FF002255"
                                  BorderThickness="1,1,1,5"
                                  IsExpanded="True">
                          <Expander.Header>
                            <DockPanel>
                              <TextBlock Width="100"
                                         Margin="5,0,0,0"
                                         FontWeight="Bold"
                                         Foreground="WhiteSmoke"
                                         Text="{Binding Path=Name,
                                                        Converter={StaticResource GenreToTextConverterKey}}" />
                              <!--
                                <TextBlock FontWeight="Bold"
                                Foreground="WhiteSmoke"
                                Text="{Binding Path=Film.Genre}" />
                              -->
                            </DockPanel>
                          </Expander.Header>
                          <Expander.Content>
                            <ItemsPresenter />
                          </Expander.Content>
                        </Expander>
                      </ControlTemplate>
                    </Setter.Value>
                  </Setter>
                </Style>
              </GroupStyle.ContainerStyle>
            </GroupStyle>
    
          </DataGrid.GroupStyle>
    
        </DataGrid>
    
      </Grid>
    </Window>


    16 июля 2014 г. 12:33