2017-09-19 69 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(); 
    } 
}