2016-07-07 78 views
3

我有一個ItemsControl綁定到綁定到查看模型上屬性的CollectionViewSource綁定GroupStyle標頭未更新收集更改時

ItemsControlGroupStyle一套看起來是這樣的:

<GroupStyle HeaderTemplate="{StaticResource TotalDurationTemplate}" /> 

其中TotalDurationTemplate是:

<DataTemplate x:Key="TotalDurationTemplate"> 
    <Border BorderBrush="Black" BorderThickness="0 1" Background="#EEE"> 
     <Grid> 
      <TextBlock HorizontalAlignment="Center" 
              FontSize="18" FontWeight="Bold" 
              Text="{Binding Path=Items[0].Start, Converter={StaticResource DateTimeFormatConverter}, ConverterParameter='ddd dd/MM'}" /> 
      <TextBlock Margin="10 0" HorizontalAlignment="Right" VerticalAlignment="Center" 
              FontSize="16" Foreground="#9000" 
              Text="{Binding Items, Converter={StaticResource TotalDurationConverter}}" /> 
     </Grid> 
    </Border> 
</DataTemplate> 

的問題是,第二TextBlock(綁定到Items一)不重 - 將新項目添加到View Model的集合(這是一個ObservableCollection<>)時評估。該項目被添加到ListView到正確的組中,但總持續時間值不會更新。

的總時間轉換看起來是這樣的:

public class TotalDurationConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return 
      ((IEnumerable<object>)value) 
       .Select(x => ((RecentTimingViewModel)x).Duration) 
       .Aggregate((v1, v2) => v1 + v2) 
       .TotalHours 
       .ToString("F2") + "h"; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new InvalidOperationException(); 
    } 
} 

如何讓我的綁定刷新正確時,在視圖模型的項目被改變了嗎?

編輯:解

我把方案二從接受的答案,並把它放到我的代碼。這是結束了工作:

<DataTemplate x:Key="TotalDurationTemplate"> 
    <Border BorderBrush="Black" BorderThickness="0 1" Background="#EEE"> 
     <Grid> 
      <TextBlock HorizontalAlignment="Center" 
         FontSize="18" FontWeight="Bold" 
         Text="{Binding Path=Items[0].Start, Converter={StaticResource FormatDateIntelligentConverter}}" /> 
      <TextBlock Margin="10 0" HorizontalAlignment="Right" VerticalAlignment="Center" 
         FontSize="16" Foreground="#9000"> 
       <TextBlock.Text> 
        <MultiBinding Converter="{StaticResource TotalDurationConverter}"> 
         <MultiBinding.Bindings> 
          <Binding Path="Items" /> 
          <Binding Path="Items.Count" /> 
         </MultiBinding.Bindings> 
        </MultiBinding> 
       </TextBlock.Text> 
      </TextBlock> 
     </Grid> 
    </Border> 
</DataTemplate> 

和不斷變化的TotalDurationConverterIMultiValueConverter。只是忽略Array中的第二項。

回答

1

所以有兩種可能性,如果你可以嘗試下面簡單的解決方案,讓我知道它是否工作。

解決方案1 ​​ - 一個非常簡單和基本的方法,因爲您使用textbloxk將模式明確設置爲雙向。我猜TextBlock默認綁定模式是一種方法。

解決方案2 - 我曾經面臨類似的問題,有一個組合工作盒 - 這裏是圍繞工作對我來說 對於第二個文本塊使用多綁定,首先將其綁定到列表,你已經做了工作,第二個將它綁定到視圖模型中的任何屬性,當列表發生變化時將觸發它(例如返回List.Count的int屬性) - 第二個虛擬屬性將確保您的轉換器被重新評估。

我想第二個選項應該適合你。

讓我知道它是否無效。

問候, 維沙爾

+0

呀留下我想結合在一個MultiBinding源列表的List.Count下班後。明天再試,看看它是如何發展的。 –

+0

酷,它在我的一個場景中工作...讓我知道它是否工作。祝一切順利 :) –