2017-09-19 70 views
-2

我試圖在ItemsControl中的每個元素後添加逗號。在此SO後 Make a WPF ListBox comma separate values ...我創建了一個轉換器,並試圖在XAML代碼中使用它,但我做錯了什麼,不知道是什麼。 包含Text=","TextBlock應該使用轉換器來控制自己的VisibilityItemsControl中的逗號分隔的項目

<ItemsControl ItemsSource="{Binding RecipientsNames}" HorizontalContentAlignment="Left"> 

    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
      <WrapPanel /> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 

    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <StackPanel Orientation="Horizontal"> 

       <Button x:Name="btnContact" Click="BtnContact_Click" 
         Width="Auto" Height="14" Padding="0" BorderThickness="0" HorizontalAlignment="Left" VerticalAlignment="Top"> 
        <TextBlock Text="{Binding Path=Name}" FontSize="12" Margin="0 -2 0 -2"/> 
       </Button> 

       <TextBlock Text="," FontSize="12" Margin="0 -2 6 -2" 
        Visibility="{Binding RelativeSource={RelativeSource 
        Mode=FindAncestor, 
        AncestorType=ItemsControlItem}, 
        Converter={StaticResource IsLastItemInContainerConverter}}"/> 

      </StackPanel> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 

</ItemsControl> 

回答

1

試試這個:

<TextBlock Text="," FontSize="12" Margin="0 -2 6 -2" 
        Visibility="{Binding RelativeSource={RelativeSource 
        Mode=FindAncestor, 
        AncestorType=ContentPresenter}, 
        Converter={StaticResource IsLastItemInContainerConverter}}"/> 

public class IsLastItemInContainerConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     FrameworkElement item = (FrameworkElement)value; 
     ItemsControl ic = ItemsControl.ItemsControlFromItemContainer(item); 

     return ic.Items.IndexOf(item.DataContext) == ic.Items.Count - 1 ? Visibility.Collapsed : Visibility.Visible; 
    } 

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