1

我创建了简单DataGridTemplateColumn的包含组合框。我为Visibility整列设置了绑定,也为ItemSource和设置SelectedItem了绑定ComboBox(我需要ItemsSource为不同的行设置不同的绑定)。一切正常,直到我隐藏该列。之后(并再次显示),它们ComboBoxes是空的,但 getterItemsSourceSelectedItembinding 返回良好的值。当我调用绑定的 setter 时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>

我的视图模型:

  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隐藏(和显示)列后重置的屏幕截图。我知道隐藏是问题所在,因为感叹号显示在隐藏之后:

隐藏(和显示)列后重置组合框

任何想法?谢谢。

4

1 回答 1

0

我发现上述错误发生在组合框的 ItemsSoure 是不可为空对象(int、enum 等)的集合的情况下。如果 ItemsSource 是可为空的对象(字符串、类),则隐藏/显示包含组合框的列可以正常工作(如预期的那样)。

因此,您需要使用可为空的 Enum 类型(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 };
   }
}
于 2018-07-24T07:05:40.173 回答