(WPF) How can a separator be added between items in an ItemsControl - Bug Fixing
I found solution on this site(How can I input separator between items in an ItemsControl(click) And found bug=((( Here is it:
It hapens when I trying to resize ItemsControl(I've set property "HorizontalScrollBarVisibilit开发者_如何学运维y" to "Disable") Any ideas How should I fix this bug?
It was not easy,but I realized what shall I do to fix this bug. My idea is to use custom Convertor, but I haven't any clever thoughts How to send ConverterParameter into convertor. But I've found solution. Here is my convertor:
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;
}
}
Find parent function:
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;
}
Here is my XAML code:
<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>
Ok. Any way, If you have another idea how to fix this bug, you could post your answer here=)
精彩评论