Это было нелегко, но я понял, что мне делать, чтобы исправить эту ошибку.Моя идея состоит в том, чтобы использовать пользовательский конвертер, но у меня нет никаких умных мыслей, как отправить ConverterParameter в конвертер.Но я нашел решение.Вот мой конвертер:
public class SeparatorConverter : IValueConverter
{
private Visibility _visible;
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var element = (TextBlock) value;
element.Loaded += ElementLoaded;
return _visible;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null; //not needed
}
private static void ElementLoaded(object sender, RoutedEventArgs e)
{
var element = sender as TextBlock;
var parentItemsControl = element.FindParent(x => x is ItemsControl) as ItemsControl;
var parentPanel = element.FindParent(x => x is Panel) as Panel;
if (parentItemsControl == null || element == null || parentPanel== null)
return;
var itemText = parentPanel.FindName("MyTextBlock") as TextBlock;
var collection = parentItemsControl.ItemsSource as IEnumerable<string>;
if (itemText == null || collection == null)
return;
var list = collection.ToList();
if (list.IndexOf(itemText.Text) == list.Count() - 1) // Can be incorrect because we can have two same items
element.Visibility = Visibility.Collapsed;
}
}
Найти родительскую функцию:
public static DependencyObject FindParent(this DependencyObject element, Func<DependencyObject, bool> filter)
{
DependencyObject parent = VisualTreeHelper.GetParent(element);
if (parent != null)
{
if (filter(parent))
{
return parent;
}
return FindParent(parent, filter);
}
return null;
}
Вот мой код XAML:
<Coverters:SeparatorConverter x:Key="SeparatorVisibilityConverter">
</Coverters:SeparatorConverter>
<ItemsControl Grid.Row="1" ItemsSource="{Binding Value, IsAsync=False}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel>
</WrapPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<WrapPanel>
<TextBlock x:Name="MyTextBlock" Text="{Binding}" Style="{StaticResource TextBlockInListViewItem}" TextWrapping="WrapWithOverflow"/>
<TextBlock x:Name="commaTextBlock" Style="{StaticResource TextBlockInListViewItem}" Text=", " Visibility="{Binding RelativeSource={RelativeSource Self},
Converter={StaticResource SeparatorVisibilityConverter}}"/>
</WrapPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
ОК.В любом случае, если у вас есть другая идея, как исправить эту ошибку, вы можете оставить свой ответ здесь =)