ComboBox в DataGridTemplateColumn очищается после скрытия столбца в WPF

Я создал простой DataGridTemplateColumn содержащий комбобокс. Я установил привязку для Visibility всего столбца, а также для ItemSource а также SelectedItem из ComboBox (Мне нужно иметь разные ItemsSource для разных рядов). Все работает нормально, пока я не спрячу колонку. После этого (и показать это снова), ComboBoxes пусты, но получатели ItemsSource а также SelectedItem привязка возвращает хорошие значения. Когда я вызываю сеттер SelectedItem привязка, предыдущее значение является правильным, и новое значение отображается в ComboBox, Так что все правильно, но почему после скрытия столбца комбо-боксы сбрасываются даже в данные ViewModel тоже правильно и ничего не меняется

  <DataGridTemplateColumn Header="Total" Visibility="{Binding ProxyData.ReportConfigurationVM.ShowTotalRow, Source={StaticResource BindingProxy}, Converter={StaticResource BoolToVisibilityConverter}}">
     <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
           <ComboBox Width="70"
                     ItemsSource="{Binding Path=TotalsAggregationFunctions}"
                     SelectedItem="{Binding Path=SelectedTotalAggregation, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" >
           </ComboBox>
        </DataTemplate>
     </DataGridTemplateColumn.CellTemplate>
  </DataGridTemplateColumn>

Моя ViewModel:

  public enum AggregationFunction
  {
     None,
     Sum,
     Avg
  }

  private AggregationFunction selectedTotalAggregation;
  public AggregationFunction SelectedTotalAggregation
  {
     get { return this.selectedTotalAggregation; }
     set { SetField(ref this.selectedTotalAggregation, value); }  // this calls OnPropertyNotify automatically
  }

  public IEnumerable<AggregationFunction> TotalsAggregationFunctions
  {
     get
     {
        // no matter what I return, nothing works when hide the column...
        return new AggregationFunction[] { AggregationFunction.None, AggregationFunction.Sum, AggregationFunction.Avg, AggregationFunction.Min, AggregationFunction.Max };
     }
  }

Скриншот сброшенного ComboBoxes после скрыть (и показать) столбец. Я знаю, что скрыть это проблема, потому что после скрытия отображаются восклицательные знаки:

ComboBoxes сбрасывать после скрытия (и показа) столбца

Любая идея? Благодарю.

1 ответ

Я обнаружил, что описанная выше ошибка возникает в тех случаях, когда ItemsSoure в выпадающем списке представляет собой набор ненулевых объектов (int, enum и т. Д.). Если ItemsSource является обнуляемым объектом (строка, класс), скрытие / отображение столбцов, содержащих выпадающий список, работает нормально (как и ожидалось).

Так что вам нужно использовать тип Enum со значением null (Enum?), И тогда все в порядке. Обходной путь - конвертировать Enum в String или обернуть Enum в класс.

public enum AggregationFunction
{
   None,
   Sum,
   Avg
}

private AggregationFunction? selectedTotalAggregation;
public AggregationFunction? SelectedTotalAggregation
{
   get { return this.selectedTotalAggregation; }
   set { SetField(ref this.selectedTotalAggregation, value); }  // this calls OnPropertyNotify automatically
}

public IEnumerable<AggregationFunction?> TotalsAggregationFunctions
{
   get
   {
      // no matter what I return, nothing works when hide the column...
      return new AggregationFunction?[] { AggregationFunction.None, AggregationFunction.Sum, AggregationFunction.Avg, AggregationFunction.Min, AggregationFunction.Max };
   }
}
Другие вопросы по тегам