Virtualizing Wrap Panel WPF - free solution? [closed] - wpf

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I know this is a duplication of Is there a (good/free) VirtualizingWrapPanel available for WPF?, but the answer there does not work as I need it. Example: When I click on an item in partial view, it takes me to the item below it, or when I refresh my items to let changes take effect on the UI that I do behind the scenes, it scrolls to the top. So has anyone found a good, free (or cheap) solution since last year?
Now I know there is an option at http://www.binarymission.co.uk/Products/WPF_SL/virtualizingwrappanel_wpf_sl.htm and that works exactly how I need it, I just would really prefer not to spend a grand for 1 project. Even if it was like 200-300 I would have already bought it but $900 for that one control in one project (so far), I just can't justify.
Any suggestions would be much appreciated!
Anthony F Greco

Use this one: http://virtualwrappanel.codeplex.com/ .
Here's how you use it:
xmlns:local="clr-namespace:MyWinCollection"
...
<local:VirtualizingWrapPanel ..../>

The one on your original link just needs a bit of tweaking to be able to support ScrollIntoView on the parent ListView so that when you refresh you can put the selection/scroll position back where you want it.
Add this extra override to the class mentioned in the question (found here)
protected override void BringIndexIntoView(int index)
{
var currentVisibleMin = _offset.Y;
var currentVisibleMax = _offset.Y + _viewportSize.Height - ItemHeight;
var itemsPerLine = Math.Max((int)Math.Floor(_viewportSize.Width / ItemWidth), 1);
var verticalOffsetRequiredToPutItemAtTopRow = Math.Floor((double)index / itemsPerLine) * ItemHeight;
if (verticalOffsetRequiredToPutItemAtTopRow < currentVisibleMin) // if item is above visible area put it on the top row
SetVerticalOffset(verticalOffsetRequiredToPutItemAtTopRow);
else if (verticalOffsetRequiredToPutItemAtTopRow > currentVisibleMax) // if item is below visible area move to put it on bottom row
SetVerticalOffset(verticalOffsetRequiredToPutItemAtTopRow - _viewportSize.Height + ItemHeight);
}
While you are there the following couple of functions can be changed as below to improve performance
protected override Size MeasureOverride(Size availableSize)
{
if (_itemsControl == null)
{
return availableSize;
}
_isInMeasure = true;
_childLayouts.Clear();
var extentInfo = GetExtentInfo(availableSize, ItemHeight);
EnsureScrollOffsetIsWithinConstrains(extentInfo);
var layoutInfo = GetLayoutInfo(availableSize, ItemHeight, extentInfo);
RecycleItems(layoutInfo);
// Determine where the first item is in relation to previously realized items
var generatorStartPosition = _itemsGenerator.GeneratorPositionFromIndex(layoutInfo.FirstRealizedItemIndex);
var visualIndex = 0;
var currentX = layoutInfo.FirstRealizedItemLeft;
var currentY = layoutInfo.FirstRealizedLineTop;
using (_itemsGenerator.StartAt(generatorStartPosition, GeneratorDirection.Forward, true))
{
for (var itemIndex = layoutInfo.FirstRealizedItemIndex; itemIndex <= layoutInfo.LastRealizedItemIndex; itemIndex++, visualIndex++)
{
bool newlyRealized;
var child = (UIElement)_itemsGenerator.GenerateNext(out newlyRealized);
SetVirtualItemIndex(child, itemIndex);
if (newlyRealized)
{
InsertInternalChild(visualIndex, child);
}
else
{
// check if item needs to be moved into a new position in the Children collection
if (visualIndex < Children.Count)
{
if (Children[visualIndex] != child)
{
var childCurrentIndex = Children.IndexOf(child);
if (childCurrentIndex >= 0)
{
RemoveInternalChildRange(childCurrentIndex, 1);
Debug.WriteLine("Moving child from {0} to {1}", childCurrentIndex, visualIndex);
}
else
Debug.WriteLine("Inserting child {0}", visualIndex);
InsertInternalChild(visualIndex, child);
}
}
else
{
// we know that the child can't already be in the children collection
// because we've been inserting children in correct visualIndex order,
// and this child has a visualIndex greater than the Children.Count
AddInternalChild(child);
Debug.WriteLine("Adding child at {0}", Children.Count-1);
}
}
// only prepare the item once it has been added to the visual tree
_itemsGenerator.PrepareItemContainer(child);
if (newlyRealized)
child.Measure(new Size(ItemWidth, ItemHeight));
_childLayouts.Add(child, new Rect(currentX, currentY, ItemWidth, ItemHeight));
if (currentX + ItemWidth * 2 >= availableSize.Width)
{
// wrap to a new line
currentY += ItemHeight;
currentX = 0;
}
else
{
currentX += ItemWidth;
}
}
}
RemoveRedundantChildren();
UpdateScrollInfo(availableSize, extentInfo);
var desiredSize = new Size(double.IsInfinity(availableSize.Width) ? 0 : availableSize.Width,
double.IsInfinity(availableSize.Height) ? 0 : availableSize.Height);
_isInMeasure = false;
return desiredSize;
}
class RemoveRange
{
public int Start;
public int Length;
}
private void RecycleItems(ItemLayoutInfo layoutInfo)
{
Queue<RemoveRange> ranges = null;
int idx = 0;
RemoveRange nextRange = null;
foreach (UIElement child in Children)
{
var virtualItemIndex = GetVirtualItemIndex(child);
if (virtualItemIndex < layoutInfo.FirstRealizedItemIndex || virtualItemIndex > layoutInfo.LastRealizedItemIndex)
{
var generatorPosition = _itemsGenerator.GeneratorPositionFromIndex(virtualItemIndex);
if (generatorPosition.Index >= 0)
{
_itemsGenerator.Recycle(generatorPosition, 1);
}
if (nextRange == null)
nextRange = new RemoveRange() { Start = idx, Length = 1 };
else
nextRange.Length++;
}
else if (nextRange!= null)
{
if (ranges== null)
ranges = new Queue<RemoveRange>();
ranges.Enqueue(nextRange);
nextRange = null;
}
SetVirtualItemIndex(child, -1);
idx++;
}
if (nextRange != null)
{
if (ranges == null)
ranges = new Queue<RemoveRange>();
ranges.Enqueue(nextRange);
}
int removed = 0;
if (ranges != null)
{
foreach (var range in ranges)
{
RemoveInternalChildRange(range.Start-removed, range.Length);
removed +=range.Length;
}
}
}

After trying to fix the issues of the http://virtualwrappanel.codeplex.com/ control I ended up with the solution from https://stackoverflow.com/a/13560758/5887121. I also added the BringIntoView method and a DP to set the orientation.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
namespace Wpf.Controls
{
// class from: https://github.com/samueldjack/VirtualCollection/blob/master/VirtualCollection/VirtualCollection/VirtualizingWrapPanel.cs
// MakeVisible() method from: http://www.switchonthecode.com/tutorials/wpf-tutorial-implementing-iscrollinfo
public class VirtualizingWrapPanel : VirtualizingPanel, IScrollInfo
{
private const double ScrollLineAmount = 16.0;
private Size _extentSize;
private Size _viewportSize;
private Point _offset;
private ItemsControl _itemsControl;
private readonly Dictionary<UIElement, Rect> _childLayouts = new Dictionary<UIElement, Rect>();
public static readonly DependencyProperty ItemWidthProperty =
DependencyProperty.Register("ItemWidth", typeof(double), typeof(VirtualizingWrapPanel), new PropertyMetadata(1.0, HandleItemDimensionChanged));
public static readonly DependencyProperty ItemHeightProperty =
DependencyProperty.Register("ItemHeight", typeof(double), typeof(VirtualizingWrapPanel), new PropertyMetadata(1.0, HandleItemDimensionChanged));
private static readonly DependencyProperty VirtualItemIndexProperty =
DependencyProperty.RegisterAttached("VirtualItemIndex", typeof(int), typeof(VirtualizingWrapPanel), new PropertyMetadata(-1));
private IRecyclingItemContainerGenerator _itemsGenerator;
private bool _isInMeasure;
private static int GetVirtualItemIndex(DependencyObject obj)
{
return (int)obj.GetValue(VirtualItemIndexProperty);
}
private static void SetVirtualItemIndex(DependencyObject obj, int value)
{
obj.SetValue(VirtualItemIndexProperty, value);
}
#region Orientation
/// <summary>
/// Gets and sets the orientation of the panel.
/// </summary>
/// <value>The orientation of the panel.</value>
public Orientation Orientation
{
get
{
return (Orientation)GetValue(OrientationProperty);
}
set
{
SetValue(OrientationProperty, value);
}
}
/// <summary>
/// Identifies the Orientation dependency property.
/// </summary>
/// <remarks>
/// Returns: The identifier for the Orientation dependency property.
/// </remarks>
public static readonly DependencyProperty OrientationProperty = StackPanel.OrientationProperty.AddOwner(typeof(VirtualizingWrapPanel), new FrameworkPropertyMetadata(Orientation.Horizontal));
#endregion Orientation
public double ItemHeight
{
get
{
return (double)GetValue(ItemHeightProperty);
}
set
{
SetValue(ItemHeightProperty, value);
}
}
public double ItemWidth
{
get
{
return (double)GetValue(ItemWidthProperty);
}
set
{
SetValue(ItemWidthProperty, value);
}
}
public VirtualizingWrapPanel()
{
if ( !DesignerProperties.GetIsInDesignMode(this) )
{
Dispatcher.BeginInvoke((Action)Initialize);
}
}
private void Initialize()
{
_itemsControl = ItemsControl.GetItemsOwner(this);
_itemsGenerator = (IRecyclingItemContainerGenerator)ItemContainerGenerator;
InvalidateMeasure();
}
protected override void OnItemsChanged(object sender, ItemsChangedEventArgs args)
{
base.OnItemsChanged(sender, args);
InvalidateMeasure();
}
protected override Size MeasureOverride(Size availableSize)
{
if ( _itemsControl == null )
{
return availableSize;
}
_isInMeasure = true;
_childLayouts.Clear();
var extentInfo = GetExtentInfo(availableSize);
EnsureScrollOffsetIsWithinConstrains(extentInfo);
var layoutInfo = GetLayoutInfo(availableSize, (Orientation == Orientation.Vertical) ? ItemHeight : ItemWidth, extentInfo);
RecycleItems(layoutInfo);
// Determine where the first item is in relation to previously realized items
var generatorStartPosition = _itemsGenerator.GeneratorPositionFromIndex(layoutInfo.FirstRealizedItemIndex);
var visualIndex = 0;
Double currentX = layoutInfo.FirstRealizedItemLeft;
Double currentY = layoutInfo.FirstRealizedLineTop;
using ( _itemsGenerator.StartAt(generatorStartPosition, GeneratorDirection.Forward, true) )
{
for ( var itemIndex = layoutInfo.FirstRealizedItemIndex ; itemIndex <= layoutInfo.LastRealizedItemIndex ; itemIndex++, visualIndex++ )
{
bool newlyRealized;
var child = (UIElement)_itemsGenerator.GenerateNext(out newlyRealized);
SetVirtualItemIndex(child, itemIndex);
if ( newlyRealized )
{
InsertInternalChild(visualIndex, child);
}
else
{
// check if item needs to be moved into a new position in the Children collection
if ( visualIndex < Children.Count )
{
if ( Children[visualIndex] != child )
{
var childCurrentIndex = Children.IndexOf(child);
if ( childCurrentIndex >= 0 )
{
RemoveInternalChildRange(childCurrentIndex, 1);
}
InsertInternalChild(visualIndex, child);
}
}
else
{
// we know that the child can't already be in the children collection
// because we've been inserting children in correct visualIndex order,
// and this child has a visualIndex greater than the Children.Count
AddInternalChild(child);
}
}
// only prepare the item once it has been added to the visual tree
_itemsGenerator.PrepareItemContainer(child);
child.Measure(new Size(ItemWidth, ItemHeight));
_childLayouts.Add(child, new Rect(currentX, currentY, ItemWidth, ItemHeight));
if ( Orientation == Orientation.Vertical )
{
if ( currentX + ItemWidth * 2 > availableSize.Width )
{
// wrap to a new line
currentY += ItemHeight;
currentX = 0;
}
else
{
currentX += ItemWidth;
}
}
else
{
if ( currentY + ItemHeight * 2 > availableSize.Height )
{
// wrap to a new column
currentX += ItemWidth;
currentY = 0;
}
else
{
currentY += ItemHeight;
}
}
}
}
RemoveRedundantChildren();
UpdateScrollInfo(availableSize, extentInfo);
var desiredSize = new Size(double.IsInfinity(availableSize.Width) ? 0 : availableSize.Width,
double.IsInfinity(availableSize.Height) ? 0 : availableSize.Height);
_isInMeasure = false;
return desiredSize;
}
private void EnsureScrollOffsetIsWithinConstrains(ExtentInfo extentInfo)
{
if ( Orientation == Orientation.Vertical )
{
_offset.Y = Clamp(_offset.Y, 0, extentInfo.MaxVerticalOffset);
}
else
{
_offset.X = Clamp(_offset.X, 0, extentInfo.MaxHorizontalOffset);
}
}
private void RecycleItems(ItemLayoutInfo layoutInfo)
{
foreach ( UIElement child in Children )
{
var virtualItemIndex = GetVirtualItemIndex(child);
if ( virtualItemIndex < layoutInfo.FirstRealizedItemIndex || virtualItemIndex > layoutInfo.LastRealizedItemIndex )
{
var generatorPosition = _itemsGenerator.GeneratorPositionFromIndex(virtualItemIndex);
if ( generatorPosition.Index >= 0 )
{
_itemsGenerator.Recycle(generatorPosition, 1);
}
}
SetVirtualItemIndex(child, -1);
}
}
protected override Size ArrangeOverride(Size finalSize)
{
foreach ( UIElement child in Children )
{
child.Arrange(_childLayouts[child]);
}
return finalSize;
}
private void UpdateScrollInfo(Size availableSize, ExtentInfo extentInfo)
{
_viewportSize = availableSize;
if ( Orientation == Orientation.Vertical )
{
_extentSize = new Size(availableSize.Width, extentInfo.ExtentHeight);
}
else
{
_extentSize = new Size(extentInfo.ExtentWidth, availableSize.Height);
}
InvalidateScrollInfo();
}
private void RemoveRedundantChildren()
{
// iterate backwards through the child collection because we're going to be
// removing items from it
for ( var i = Children.Count - 1 ; i >= 0 ; i-- )
{
var child = Children[i];
// if the virtual item index is -1, this indicates
// it is a recycled item that hasn't been reused this time round
if ( GetVirtualItemIndex(child) == -1 )
{
RemoveInternalChildRange(i, 1);
}
}
}
private ItemLayoutInfo GetLayoutInfo(Size availableSize, double itemHeightOrWidth, ExtentInfo extentInfo)
{
if ( _itemsControl == null )
{
return new ItemLayoutInfo();
}
// we need to ensure that there is one realized item prior to the first visible item, and one after the last visible item,
// so that keyboard navigation works properly. For example, when focus is on the first visible item, and the user
// navigates up, the ListBox selects the previous item, and the scrolls that into view - and this triggers the loading of the rest of the items
// in that row
if ( Orientation == Orientation.Vertical )
{
var firstVisibleLine = (int)Math.Floor(VerticalOffset / itemHeightOrWidth);
var firstRealizedIndex = Math.Max(extentInfo.ItemsPerLine * firstVisibleLine - 1, 0);
var firstRealizedItemLeft = firstRealizedIndex % extentInfo.ItemsPerLine * ItemWidth - HorizontalOffset;
var firstRealizedItemTop = (firstRealizedIndex / extentInfo.ItemsPerLine) * itemHeightOrWidth - VerticalOffset;
var firstCompleteLineTop = (firstVisibleLine == 0 ? firstRealizedItemTop : firstRealizedItemTop + ItemHeight);
var completeRealizedLines = (int)Math.Ceiling((availableSize.Height - firstCompleteLineTop) / itemHeightOrWidth);
var lastRealizedIndex = Math.Min(firstRealizedIndex + completeRealizedLines * extentInfo.ItemsPerLine + 2, _itemsControl.Items.Count - 1);
return new ItemLayoutInfo
{
FirstRealizedItemIndex = firstRealizedIndex,
FirstRealizedItemLeft = firstRealizedItemLeft,
FirstRealizedLineTop = firstRealizedItemTop,
LastRealizedItemIndex = lastRealizedIndex,
};
}
else
{
var firstVisibleColumn = (int)Math.Floor(HorizontalOffset / itemHeightOrWidth);
var firstRealizedIndex = Math.Max(extentInfo.ItemsPerColumn * firstVisibleColumn - 1, 0);
var firstRealizedItemTop = firstRealizedIndex % extentInfo.ItemsPerColumn * ItemHeight - VerticalOffset;
var firstRealizedItemLeft = (firstRealizedIndex / extentInfo.ItemsPerColumn) * itemHeightOrWidth - HorizontalOffset;
var firstCompleteColumnLeft = (firstVisibleColumn == 0 ? firstRealizedItemLeft : firstRealizedItemLeft + ItemWidth);
var completeRealizedColumns = (int)Math.Ceiling((availableSize.Width - firstCompleteColumnLeft) / itemHeightOrWidth);
var lastRealizedIndex = Math.Min(firstRealizedIndex + completeRealizedColumns * extentInfo.ItemsPerColumn + 2, _itemsControl.Items.Count - 1);
return new ItemLayoutInfo
{
FirstRealizedItemIndex = firstRealizedIndex,
FirstRealizedItemLeft = firstRealizedItemLeft,
FirstRealizedLineTop = firstRealizedItemTop,
LastRealizedItemIndex = lastRealizedIndex,
};
}
}
private ExtentInfo GetExtentInfo(Size viewPortSize)
{
if ( _itemsControl == null )
{
return new ExtentInfo();
}
if ( Orientation == Orientation.Vertical )
{
var itemsPerLine = Math.Max((int)Math.Floor(viewPortSize.Width / ItemWidth), 1);
var totalLines = (int)Math.Ceiling((double)_itemsControl.Items.Count / itemsPerLine);
var extentHeight = Math.Max(totalLines * ItemHeight, viewPortSize.Height);
return new ExtentInfo
{
ItemsPerLine = itemsPerLine,
TotalLines = totalLines,
ExtentHeight = extentHeight,
MaxVerticalOffset = extentHeight - viewPortSize.Height,
};
}
else
{
var itemsPerColumn = Math.Max((int)Math.Floor(viewPortSize.Height / ItemHeight), 1);
var totalColumns = (int)Math.Ceiling((double)_itemsControl.Items.Count / itemsPerColumn);
var extentWidth = Math.Max(totalColumns * ItemWidth, viewPortSize.Width);
return new ExtentInfo
{
ItemsPerColumn = itemsPerColumn,
TotalColumns = totalColumns,
ExtentWidth = extentWidth,
MaxHorizontalOffset = extentWidth - viewPortSize.Width
};
}
}
public void LineUp()
{
SetVerticalOffset(VerticalOffset - ScrollLineAmount);
}
public void LineDown()
{
SetVerticalOffset(VerticalOffset + ScrollLineAmount);
}
public void LineLeft()
{
SetHorizontalOffset(HorizontalOffset - ScrollLineAmount);
}
public void LineRight()
{
SetHorizontalOffset(HorizontalOffset + ScrollLineAmount);
}
public void PageUp()
{
SetVerticalOffset(VerticalOffset - ViewportHeight);
}
public void PageDown()
{
SetVerticalOffset(VerticalOffset + ViewportHeight);
}
public void PageLeft()
{
SetHorizontalOffset(HorizontalOffset - ItemWidth);
}
public void PageRight()
{
SetHorizontalOffset(HorizontalOffset + ItemWidth);
}
public void MouseWheelUp()
{
if ( Orientation == Orientation.Vertical )
{
SetVerticalOffset(VerticalOffset - ScrollLineAmount * SystemParameters.WheelScrollLines);
}
else
{
MouseWheelLeft();
}
}
public void MouseWheelDown()
{
if ( Orientation == Orientation.Vertical )
{
SetVerticalOffset(VerticalOffset + ScrollLineAmount * SystemParameters.WheelScrollLines);
}
else
{
MouseWheelRight();
}
}
public void MouseWheelLeft()
{
SetHorizontalOffset(HorizontalOffset - ScrollLineAmount * SystemParameters.WheelScrollLines);
}
public void MouseWheelRight()
{
SetHorizontalOffset(HorizontalOffset + ScrollLineAmount * SystemParameters.WheelScrollLines);
}
public void SetHorizontalOffset(double offset)
{
if ( _isInMeasure )
{
return;
}
offset = Clamp(offset, 0, ExtentWidth - ViewportWidth);
_offset = new Point(offset, _offset.Y);
InvalidateScrollInfo();
InvalidateMeasure();
}
public void SetVerticalOffset(double offset)
{
if ( _isInMeasure )
{
return;
}
offset = Clamp(offset, 0, ExtentHeight - ViewportHeight);
_offset = new Point(_offset.X, offset);
InvalidateScrollInfo();
InvalidateMeasure();
}
public Rect MakeVisible(Visual visual, Rect rectangle)
{
if ( rectangle.IsEmpty ||
visual == null ||
visual == this ||
!IsAncestorOf(visual) )
{
return Rect.Empty;
}
rectangle = visual.TransformToAncestor(this).TransformBounds(rectangle);
var viewRect = new Rect(HorizontalOffset, VerticalOffset, ViewportWidth, ViewportHeight);
rectangle.X += viewRect.X;
rectangle.Y += viewRect.Y;
viewRect.X = CalculateNewScrollOffset(viewRect.Left, viewRect.Right, rectangle.Left, rectangle.Right);
viewRect.Y = CalculateNewScrollOffset(viewRect.Top, viewRect.Bottom, rectangle.Top, rectangle.Bottom);
SetHorizontalOffset(viewRect.X);
SetVerticalOffset(viewRect.Y);
rectangle.Intersect(viewRect);
rectangle.X -= viewRect.X;
rectangle.Y -= viewRect.Y;
return rectangle;
}
private static double CalculateNewScrollOffset(double topView, double bottomView, double topChild, double bottomChild)
{
var offBottom = topChild < topView && bottomChild < bottomView;
var offTop = bottomChild > bottomView && topChild > topView;
var tooLarge = (bottomChild - topChild) > (bottomView - topView);
if ( !offBottom && !offTop )
return topView;
if ( (offBottom && !tooLarge) || (offTop && tooLarge) )
return topChild;
return bottomChild - (bottomView - topView);
}
public ItemLayoutInfo GetVisibleItemsRange()
{
return GetLayoutInfo(_viewportSize, (Orientation == Orientation.Vertical) ? ItemHeight : ItemWidth, GetExtentInfo(_viewportSize));
}
protected override void BringIndexIntoView(int index)
{
if ( Orientation == Orientation.Vertical )
{
var currentVisibleMin = _offset.Y;
var currentVisibleMax = _offset.Y + _viewportSize.Height - ItemHeight;
var itemsPerLine = Math.Max((int)Math.Floor(_viewportSize.Width / ItemWidth), 1);
var verticalOffsetRequiredToPutItemAtTopRow = Math.Floor((double)index / itemsPerLine) * ItemHeight;
if ( verticalOffsetRequiredToPutItemAtTopRow < currentVisibleMin ) // if item is above visible area put it on the top row
SetVerticalOffset(verticalOffsetRequiredToPutItemAtTopRow);
else if ( verticalOffsetRequiredToPutItemAtTopRow > currentVisibleMax ) // if item is below visible area move to put it on bottom row
SetVerticalOffset(verticalOffsetRequiredToPutItemAtTopRow - _viewportSize.Height + ItemHeight);
}
else
{
var currentVisibleMin = _offset.X;
var currentVisibleMax = _offset.X + _viewportSize.Width - ItemWidth;
var itemsPerColumn = Math.Max((int)Math.Floor(_viewportSize.Height / ItemHeight), 1);
var horizontalOffsetRequiredToPutItemAtLeftRow = Math.Floor((double)index / itemsPerColumn) * ItemWidth;
if ( horizontalOffsetRequiredToPutItemAtLeftRow < currentVisibleMin ) // if item is left from the visible area put it at the left most column
SetHorizontalOffset(horizontalOffsetRequiredToPutItemAtLeftRow);
else if ( horizontalOffsetRequiredToPutItemAtLeftRow > currentVisibleMax ) // if item is right from the visible area put it at the right most column
SetHorizontalOffset(horizontalOffsetRequiredToPutItemAtLeftRow - _viewportSize.Width + ItemWidth);
}
}
public bool CanVerticallyScroll
{
get;
set;
}
public bool CanHorizontallyScroll
{
get;
set;
}
public double ExtentWidth
{
get
{
return _extentSize.Width;
}
}
public double ExtentHeight
{
get
{
return _extentSize.Height;
}
}
public double ViewportWidth
{
get
{
return _viewportSize.Width;
}
}
public double ViewportHeight
{
get
{
return _viewportSize.Height;
}
}
public double HorizontalOffset
{
get
{
return _offset.X;
}
}
public double VerticalOffset
{
get
{
return _offset.Y;
}
}
public ScrollViewer ScrollOwner
{
get;
set;
}
private void InvalidateScrollInfo()
{
if ( ScrollOwner != null )
{
ScrollOwner.InvalidateScrollInfo();
}
}
private static void HandleItemDimensionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var wrapPanel = (d as VirtualizingWrapPanel);
if ( wrapPanel != null )
wrapPanel.InvalidateMeasure();
}
private double Clamp(double value, double min, double max)
{
return Math.Min(Math.Max(value, min), max);
}
internal class ExtentInfo
{
public int ItemsPerLine;
public Int32 ItemsPerColumn;
public int TotalLines;
public Int32 TotalColumns;
public double ExtentHeight;
public double ExtentWidth;
public double MaxVerticalOffset;
public double MaxHorizontalOffset;
}
public class ItemLayoutInfo
{
public int FirstRealizedItemIndex;
public double FirstRealizedLineTop;
public double FirstRealizedItemLeft;
public int LastRealizedItemIndex;
}
}
}

I was searching a week for some solution and than I had idea how to fake VirtualizingWrapPanel.
If you know width of your Items, than you can create "rows" as StackPanel and these rows render in VirtualizingStackPanel.
XAML
<ItemsControl x:Name="Thumbs" VirtualizingStackPanel.IsVirtualizing="True"
VirtualizingPanel.ScrollUnit="Pixel" ScrollViewer.CanContentScroll="True">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Width="{Binding ThumbWidth}" Height="{Binding ThumbHeight}"
BorderThickness="2" BorderBrush="Black" ClipToBounds="True">
<Image Source="{Binding FilePathCacheUri}" Stretch="Fill" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.Template>
<ControlTemplate>
<ScrollViewer>
<ItemsPresenter />
</ScrollViewer>
</ControlTemplate>
</ItemsControl.Template>
</ItemsControl>
C#
public List<BaseMediaItem> MediaItems { get; set; }
public List<List<BaseMediaItem>> SplitedMediaItems { get; set; }
public MainWindow() {
InitializeComponent();
DataContext = this;
MediaItems = new List<BaseMediaItem>();
SplitedMediaItems = new List<List<BaseMediaItem>>();
}
private void MainWindow_OnLoaded(object sender, RoutedEventArgs e) {
LoadMediaItems();
SplitMediaItems();
Thumbs.ItemsSource = SplitedMediaItems;
}
public void LoadMediaItems() {
var sizes = new List<Point> {new Point(320, 180), new Point(320, 240), new Point(180, 320), new Point(240, 320)};
MediaItems.Clear();
var random = new Random();
for (var i = 0; i < 5000; i++) {
var size = sizes[random.Next(sizes.Count)];
MediaItems.Add(new BaseMediaItem($"Item {i}") {
ThumbWidth = (int)size.X,
ThumbHeight = (int)size.Y
});
}
}
public void SplitMediaItems() {
foreach (var itemsGroup in SplitedMediaItems) {
itemsGroup.Clear();
}
SplitedMediaItems.Clear();
var groupMaxWidth = Thumbs.ActualWidth;
var groupWidth = 0;
const int itemOffset = 6; //border, margin, padding, ...
var row = new List<BaseMediaItem>();
foreach (var item in MediaItems) {
if (item.ThumbWidth + itemOffset <= groupMaxWidth - groupWidth) {
row.Add(item);
groupWidth += item.ThumbWidth + itemOffset;
}
else {
SplitedMediaItems.Add(row);
row = new List<BaseMediaItem>();
row.Add(item);
groupWidth = item.ThumbWidth + itemOffset;
}
}
SplitedMediaItems.Add(row);
}

Related

Winforms: Controls not visible after added programmatically

I want to create a simple FileExplorer Control for a video player.
Here is the code:
namespace CustomControls
{
public interface IScrollable
{
float visiblePercent { get; set; }
float ScrollSpeedMultiplier { get; set; }
int scrollValue { get; set; }
CustomScrollBar scrollBar { get; set; }
}
}
namespace CustomControls {
public partial class ScrollablePanel : UserControl, IScrollable {
private int _scrollValue;
private int _totalWheelDelta;
private int totalWheelDelta {
get => _totalWheelDelta;
set {
SetTotalDelta(value);
}
}
public int Count => panelInner.Controls.Count;
public bool VisibleControls => panelInner.Controls.OfType<Panel>().All(p => p.Visible);
public float visiblePercent { get; set; }
public int scrollValue {
get { return _scrollValue; }
set {
_scrollValue = value;
if (scrollBar != null && scrollBar.value != _scrollValue)
scrollBar.value = _scrollValue;
SetTotalDeltaByScrollValue(value);
ScrollThrough();
}
}
[EditorBrowsable(EditorBrowsableState.Always), Browsable(true), DefaultValue(0), Category("Behavior"), Description("Die dazugehörige Scrollbar")]
public CustomScrollBar scrollBar { get; set; }
public float ScrollSpeedMultiplier { get; set; }
public ScrollablePanel() {
InitializeComponent();
panelInner.MouseWheel += panelInner_MouseWheel;
}
protected override ControlCollection CreateControlsInstance() {
return new ScrollablePanelElementCollection(this, this.panelInner);
}
private void ScrollablePanel_Load(object sender, EventArgs e) {
OnControlsChanged();
}
private void panelInner_MouseWheel(object sender, MouseEventArgs e) {
if (visiblePercent >= 1.0f)
return;
totalWheelDelta += (int)(e.Delta * ScrollSpeedMultiplier);
scrollValue = (100 * SystemInformation.MouseWheelScrollLines * totalWheelDelta) / ((Height - panelInner.Height) * SystemData.scrollDeltaModifier);
if (scrollBar != null)
scrollValue = scrollBar.value = (100 * SystemInformation.MouseWheelScrollLines * totalWheelDelta) / ((Height - panelInner.Height) * SystemData.scrollDeltaModifier);
}
private void ScrollThrough() {
panelInner.Location = new Point(0, (int)((Height - panelInner.Height) * (scrollValue / 100.0f)));
}
private void panelInner_ControlAdded(object sender, ControlEventArgs e) {
OnControlsChanged();
}
private void panelInner_ControlRemoved(object sender, ControlEventArgs e) {
OnControlsChanged();
}
private void OnControlsChanged() {
int height = int.MinValue;
foreach (Control control in panelInner.Controls)
if (control.Visible)
height = Math.Max(height, control.Bottom);
panelInner.Height = height;
ScrollablePanel_Resize(this, new EventArgs());
if (panelInner.Height > 0)
visiblePercent = (float)Height / panelInner.Height;
else
visiblePercent = 1.0f;
if (scrollBar != null)
scrollBar.largeChange = (int)(visiblePercent * 100);
}
private void ScrollablePanel_Resize(object sender, EventArgs e) {
panelInner.Width = Width;
}
private void SetTotalDelta(int value) {
int lines = SystemInformation.MouseWheelScrollLines * (value / SystemData.scrollDeltaModifier);
int deltaHeight = Height - panelInner.Height;
if (lines > 0)
_totalWheelDelta = 0;
else if (lines < deltaHeight)
_totalWheelDelta = (deltaHeight * SystemData.scrollDeltaModifier) / SystemInformation.MouseWheelScrollLines;
else
_totalWheelDelta = value;
}
private void SetTotalDeltaByScrollValue(int value) {
int deltaHeight = Height - panelInner.Height;
totalWheelDelta = (deltaHeight * SystemData.scrollDeltaModifier * scrollValue) / (100 * SystemInformation.MouseWheelScrollLines);
}
public void Clear() {
panelInner.Controls.Clear();
}
}
public class ScrollablePanelElementCollection : Control.ControlCollection {
private Control container;
public ScrollablePanelElementCollection(Control owner, Panel container) : base(owner) { this.container = container; }
public override void Add(Control value) {
if (this.Count == 0)
base.Add(value);
else
container.Controls.Add(value);
}
}
}
namespace MagererPlayer {
public partial class FileExplorer : UserControl, IScrollable {
private string _directory;
public float visiblePercent {
get => scrollablePanel.visiblePercent;
set => scrollablePanel.visiblePercent = value;
}
public int scrollValue {
get => scrollablePanel.scrollValue;
set => scrollablePanel.scrollValue = value;
}
public CustomScrollBar scrollBar {
get => scrollablePanel.scrollBar;
set => scrollablePanel.scrollBar = value;
}
public string Directory {
get => this._directory;
set {
if (System.IO.Directory.Exists(value)) {
this._directory = value;
GetDirectory();
}
}
}
public float ScrollSpeedMultiplier { get; set; }
public EventHandler OnDirectoryChanged = null;
public EventHandler<FileSelectedEventArgs> OnFileSelected = null;
public FileExplorer() {
InitializeComponent();
}
private void FileExplorer_Load(object sender, EventArgs e) {
AdjustSize();
}
private void FileExplorer_Resize(object sender, EventArgs e) {
AdjustSize();
}
private void AdjustSize() {
}
private void GetDirectory() {
scrollablePanel.Clear();
System.Diagnostics.Trace.WriteLine(this.Directory);
int offset = System.IO.Directory.GetParent(this.Directory) != null ? 1 : 0;
int colCount = scrollablePanel.Width / 145;
string[] dirs = System.IO.Directory.GetDirectories(new string(this.Directory.Where(c => !char.IsControl(c)).ToArray()));
Array.Sort(dirs);
if (offset == 1) {
DirectoryInfo parent = System.IO.Directory.GetParent(this.Directory);
scrollablePanel.Controls.Add(GetExplorerItem(parent.FullName, "..", new Point(0, 0)));
}
for (int i = 0; i < dirs.Length; i++)
scrollablePanel.Controls.Add(GetExplorerItem(dirs[i], new DirectoryInfo(dirs[i]).Name, new Point(((i + offset) % colCount) * 145, (i + offset) / colCount * 115 + 10)));
offset += dirs.Length;
dirs = System.IO.Directory.GetFiles(new string(this.Directory.Where(c => !char.IsControl(c)).ToArray()), "*.mp4", SearchOption.TopDirectoryOnly);
Array.Sort(dirs);
for (int i = 0; i < dirs.Length; i++)
scrollablePanel.Controls.Add(GetExplorerItem(dirs[i], new FileInfo(dirs[i]).Name, new Point(((i + offset) % colCount) * 145, (i + offset) / colCount * 115 + 10)));
System.Diagnostics.Trace.WriteLine(scrollablePanel.Count);
System.Diagnostics.Trace.WriteLine(scrollablePanel.VisibleControls);
this.Invalidate();
}
private Panel GetExplorerItem(string path, string text, Point location) {
BunifuImageButton bunifuImageButton = new BunifuImageButton();
Label label = new Label();
Panel panel = new Panel();
if (System.IO.Directory.Exists(path)) {
bunifuImageButton.Image = Properties.Resources.folder;
bunifuImageButton.Click += delegate (object sender, EventArgs e) {
this.Directory = path;
};
} else if (System.IO.File.Exists(path)) {
bunifuImageButton.Image = Properties.Resources.video_1;
}
bunifuImageButton.ImageActive = null;
bunifuImageButton.Location = new System.Drawing.Point(10, 0);
bunifuImageButton.Name = "bunifuImageButton";
bunifuImageButton.Size = new System.Drawing.Size(125, 70);
bunifuImageButton.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
bunifuImageButton.TabStop = false;
bunifuImageButton.Zoom = 5;
bunifuImageButton.Cursor = Cursors.Hand;
label.Font = new System.Drawing.Font("Century Gothic", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0);
label.ForeColor = System.Drawing.Color.FromArgb(224, 224, 224);
label.Name = "label";
label.Dock = DockStyle.Bottom;
label.Size = new Size(145, 40);
label.Text = text;
label.TextAlign = ContentAlignment.MiddleCenter;
label.AutoEllipsis = true;
panel.Controls.Add(bunifuImageButton);
panel.Controls.Add(label);
panel.Location = location;
panel.Name = "panel";
panel.Size = new System.Drawing.Size(145, 110);
return panel;
}
private void textBoxUrl_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Enter) {
this.Directory = this.textBoxUrl.Text;
this.textBoxUrl.Text = this.Directory;
}
}
}
public class FileSelectedEventArgs : EventArgs {
public FileInfo File { get; }
public FileSelectedEventArgs(string path) {
File = new FileInfo(path);
}
public FileSelectedEventArgs(FileInfo info) {
File = info;
}
}
}
The Scrollable panel contains an inner panel that gets moved up and down. The FileExplorer contains a textbox for the URL, a button, and a scrollable panel.
My problem is that when I run the application everything works fine. When I go to the parent folder (IMPORTANT, NOT A SUBDIR) and reenter the folder all controls that should be there are invisible, but they were added to the inner panel's control collection.
This is the only folder dir where this error occurs: D:\Serien\Anime\Yu-Gi-Oh! Zexal
Output of System.Diagnostics from FileExplorer.GetDirectory:
D:\Serien\Anime\Yu-Gi-Oh! Zexal
3
True
D:\Serien\Anime
47
True
D:\Serien\Anime\Yu-Gi-Oh! Zexal
3
True
Screenshot of app start:
Screenshot after reenter:

WPF VirtualizingPanel as Listview ItemsPanel : How to manage unrealized items selection / deselection?

I'm currently working on a kind of VirtualizedWrapPanel to use as the ItemsPanel in a ListView.
After following this guy's instructions, and borrowing heavily from this guy's implementation found on codeproject but I don't have the reputation to post the link so sorry..., I have something that is nicely shaping up to be exactly what I need.
The item size is fixed so the scrolling is pixel based. the orientation is always horizontal.
the ListView :
<ListView Name="lv"
ItemsSource="{Binding CV}"
IsSynchronizedWithCurrentItem="True"
ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<i:Interaction.Behaviors>
<local:ScrollToSelectionListViewBehavior/> <!-- Behavior calling ScrollIntoView whenever the selection changes -->
<local:ListViewSelectedItemsBehavior SelectedItems="{Binding SelectedItems}"/> <!-- Behavior exposing the attached ListView's SelectedItems array -->
</i:Interaction.Behaviors>
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Height="100" Width="100" Orientation="Vertical">
<Border BorderBrush="Black" BorderThickness="1" CornerRadius="5" Width="90" Height="90">
<TextBlock Text ="{Binding ItemText}" FontWeight="Bold" VerticalAlignment="Center" HorizontalAlignment="Center" />
</Border>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<local:VirtualizingWrapPanel ItemHeight="100" ItemWidth="110" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
the local:VirtualizingWrapPanel :
public class VirtualizingWrapPanel : VirtualizingPanel, IScrollInfo
{
private ScrollViewer _owner;
private const bool _canHScroll = false;
private bool _canVScroll = false;
private Size _extent = new Size(0, 0);
private Size _viewport = new Size(0, 0);
private Point _offset;
UIElementCollection _children;
ItemsControl _itemsControl;
IItemContainerGenerator _generator;
Dictionary<UIElement, Rect> _realizedChildLayout = new Dictionary<UIElement, Rect>();
#region Properties
private Size ChildSlotSize
{
get { return new Size(ItemWidth, ItemHeight); }
}
#endregion
#region Dependency Properties
[TypeConverter(typeof(LengthConverter))]
public double ItemHeight
{
get { return (double)base.GetValue(ItemHeightProperty); }
set { base.SetValue(ItemHeightProperty, value); }
}
[TypeConverter(typeof(LengthConverter))]
public double ItemWidth
{
get { return (double)base.GetValue(ItemWidthProperty); }
set { base.SetValue(ItemWidthProperty, value); }
}
public static readonly DependencyProperty ItemHeightProperty = DependencyProperty.Register("ItemHeight", typeof(double), typeof(VirtualizingWrapPanel), new FrameworkPropertyMetadata(double.PositiveInfinity));
public static readonly DependencyProperty ItemWidthProperty = DependencyProperty.Register("ItemWidth", typeof(double), typeof(VirtualizingWrapPanel), new FrameworkPropertyMetadata(double.PositiveInfinity));
private int LineCapacity
{ get { return Math.Max((_viewport.Width != 0) ? (int)(_viewport.Width / ItemWidth) : 0, 1); } }
private int LinesCount
{ get { return (ItemsCount > 0) ? ItemsCount / LineCapacity : 0 ; } }
private int ItemsCount
{ get { return _itemsControl.Items.Count; } }
public int FirstVisibleLine
{ get { return (int)(_offset.Y / ItemHeight); } }
public int FirstVisibleItemVPos
{ get { return (int)((FirstVisibleLine * ItemHeight) - _offset.Y); } }
public int FirstVisibleIndex
{ get { return (FirstVisibleLine * LineCapacity); } }
#endregion
#region VirtualizingPanel overrides
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
_itemsControl = ItemsControl.GetItemsOwner(this);
_children = InternalChildren;
_generator = ItemContainerGenerator;
this.SizeChanged += new SizeChangedEventHandler(this.Resizing);
}
protected override Size MeasureOverride(Size availableSize)
{
if (_itemsControl == null || _itemsControl.Items.Count == 0)
return availableSize;
if (availableSize != _viewport)
{
_viewport = availableSize;
if (_owner != null)
_owner.InvalidateScrollInfo();
}
Size childSize = new Size(ItemWidth, ItemHeight);
Size extent = new Size(availableSize.Width, LinesCount * ItemHeight);
if (extent != _extent)
{
_extent = extent;
if (_owner != null)
_owner.InvalidateScrollInfo();
}
foreach (UIElement child in this.InternalChildren)
{
child.Measure(childSize);
}
_realizedChildLayout.Clear();
Size realizedFrameSize = availableSize;
int firstVisibleIndex = FirstVisibleIndex;
GeneratorPosition startPos = _generator.GeneratorPositionFromIndex(firstVisibleIndex);
int childIndex = (startPos.Offset == 0) ? startPos.Index : startPos.Index + 1;
int current = firstVisibleIndex;
using (_generator.StartAt(startPos, GeneratorDirection.Forward, true))
{
bool stop = false;
double currentX = 0;
double currentY = FirstVisibleItemVPos;
while (current < ItemsCount)
{
bool newlyRealized;
// Get or create the child
UIElement child = _generator.GenerateNext(out newlyRealized) as UIElement;
if (newlyRealized)
{
// Figure out if we need to insert the child at the end or somewhere in the middle
if (childIndex >= _children.Count)
{
base.AddInternalChild(child);
}
else
{
base.InsertInternalChild(childIndex, child);
}
_generator.PrepareItemContainer(child);
child.Measure(ChildSlotSize);
}
else
{
// The child has already been created, let's be sure it's in the right spot
Debug.Assert(child == _children[childIndex], "Wrong child was generated");
}
childSize = child.DesiredSize;
Rect childRect = new Rect(new Point(currentX, currentY), childSize);
if (childRect.Right > realizedFrameSize.Width) //wrap to a new line
{
currentY = currentY + ItemHeight;
currentX = 0;
childRect.X = currentX;
childRect.Y = currentY;
}
if (currentY > realizedFrameSize.Height)
stop = true;
currentX = childRect.Right;
_realizedChildLayout.Add(child, childRect);
if (stop)
break;
current++;
childIndex++;
}
}
CleanUpItems(firstVisibleIndex, current - 1);
return availableSize;
}
public void CleanUpItems(int minDesiredGenerated, int maxDesiredGenerated)
{
for (int i = _children.Count - 1; i >= 0; i--)
{
GeneratorPosition childGeneratorPos = new GeneratorPosition(i, 0);
int itemIndex = _generator.IndexFromGeneratorPosition(childGeneratorPos);
if (itemIndex < minDesiredGenerated || itemIndex > maxDesiredGenerated)
{
//var c = _children[i] as ListViewItem;
//if(c!= null && c.IsSelected)
//{
//}
_generator.Remove(childGeneratorPos, 1);
RemoveInternalChildRange(i, 1);
}
}
}
protected override Size ArrangeOverride(Size finalSize)
{
if (finalSize != _viewport)
{
_viewport = finalSize;
if (_owner != null)
_owner.InvalidateScrollInfo();
}
Size childSize = new Size(ItemWidth, ItemHeight);
Size extent = new Size(finalSize.Width, LinesCount * ItemHeight);
if (extent != _extent)
{
_extent = extent;
if (_owner != null)
_owner.InvalidateScrollInfo();
}
if (_children != null)
{
foreach (UIElement child in _children)
{
var layoutInfo = _realizedChildLayout[child];
child.Arrange(layoutInfo);
}
}
return finalSize;
}
protected override void BringIndexIntoView(int index)
{
SetVerticalOffset((index / LineCapacity) * ItemHeight);
}
protected override void OnItemsChanged(object sender, ItemsChangedEventArgs args)
{
base.OnItemsChanged(sender, args);
_offset.X = 0;
_offset.Y = 0;
switch (args.Action)
{
case NotifyCollectionChangedAction.Remove:
case NotifyCollectionChangedAction.Replace:
RemoveInternalChildRange(args.Position.Index, args.ItemUICount);
break;
case NotifyCollectionChangedAction.Move:
RemoveInternalChildRange(args.OldPosition.Index, args.ItemUICount);
break;
}
}
#endregion
#region EventHandlers
public void Resizing(object sender, EventArgs e)
{
var args = e as SizeChangedEventArgs;
if(args.WidthChanged)
{
int lineCapacity = LineCapacity;
int previousLineCapacity = (int)(args.PreviousSize.Width / ItemWidth);
if (previousLineCapacity != lineCapacity)
{
int previousFirstItem = ((int)(_offset.Y / ItemHeight) <= 0) ? 0 : ((int)(_offset.Y / ItemHeight) * previousLineCapacity);
BringIndexIntoView(previousFirstItem);
}
}
if (_viewport.Width != 0)
{
MeasureOverride(_viewport);
}
}
#endregion
#region IScrollInfo Implementation
public ScrollViewer ScrollOwner
{
get { return _owner; }
set { _owner = value; }
}
public bool CanHorizontallyScroll
{
get { return false; }
set { if (value == true) throw (new ArgumentException("VirtualizingWrapPanel does not support Horizontal scrolling")); }
}
public bool CanVerticallyScroll
{
get { return _canVScroll; }
set { _canVScroll = value; }
}
public double ExtentHeight
{
get { return _extent.Height;}
}
public double ExtentWidth
{
get { return _extent.Width; }
}
public double HorizontalOffset
{
get { return _offset.X; }
}
public double VerticalOffset
{
get { return _offset.Y; }
}
public double ViewportHeight
{
get { return _viewport.Height; }
}
public double ViewportWidth
{
get { return _viewport.Width; }
}
public Rect MakeVisible(Visual visual, Rect rectangle)
{
var gen = (ItemContainerGenerator)_generator.GetItemContainerGeneratorForPanel(this);
var element = (UIElement)visual;
int itemIndex = gen.IndexFromContainer(element);
while (itemIndex == -1)
{
element = (UIElement)VisualTreeHelper.GetParent(element);
itemIndex = gen.IndexFromContainer(element);
}
Rect elementRect = _realizedChildLayout[element];
if (elementRect.Bottom > ViewportHeight)
{
double translation = elementRect.Bottom - ViewportHeight;
_offset.Y += translation;
}
else if (elementRect.Top < 0)
{
double translation = elementRect.Top;
_offset.Y += translation;
}
InvalidateMeasure();
return elementRect;
}
public void LineDown()
{
SetVerticalOffset(VerticalOffset + 50);
}
public void LineUp()
{
SetVerticalOffset(VerticalOffset - 50);
}
public void MouseWheelDown()
{
SetVerticalOffset(VerticalOffset + 50);
}
public void MouseWheelUp()
{
SetVerticalOffset(VerticalOffset - 50);
}
public void PageDown()
{
int fullyVisibleLines = (int)(_viewport.Height / ItemHeight);
SetVerticalOffset(VerticalOffset + (fullyVisibleLines * ItemHeight));
}
public void PageUp()
{
int fullyVisibleLines = (int)(_viewport.Height / ItemHeight);
SetVerticalOffset(VerticalOffset - (fullyVisibleLines * ItemHeight));
}
public void SetVerticalOffset(double offset)
{
if (offset < 0 || _viewport.Height >= _extent.Height)
{
offset = 0;
}
else
{
if (offset + _viewport.Height >= _extent.Height)
{
offset = _extent.Height - _viewport.Height;
}
}
_offset.Y = offset;
if (_owner != null)
_owner.InvalidateScrollInfo();
InvalidateMeasure();
}
public void LineLeft() { throw new NotImplementedException(); }
public void LineRight() { throw new NotImplementedException(); }
public void MouseWheelLeft() { throw new NotImplementedException(); }
public void MouseWheelRight() { throw new NotImplementedException(); }
public void PageLeft() { throw new NotImplementedException(); }
public void PageRight() { throw new NotImplementedException(); }
public void SetHorizontalOffset(double offset) { throw new NotImplementedException(); }
#endregion
#region methods
#endregion
}
Now my problem is : An Item Selection should always Deselect the previously selected item, when using a normal WrapPanel, the previously selected ListViewItem's IsSelected property is always set to false before the new selected ListViewItem's IsSelected is set to true.
This deselection does not happen with my VirtualizingPanel when the previously selected item is no longer realized (when it is not visible in the viewport), so I end up with two or more selected items at once and the panel's behavior becomes really weird. Sometimes it even settles into an infinite loop, the two selected items yanking visibility from each other in a never ending battle.
I searched a bit for a solution to this problem but I don't really know where to start or what to search for.
Here is a test project if you want to experiment with it.
Thanks
I found a way by preventing the virtualization of selected items. Now the control behaves correctly.
public void CleanUpItems(int minDesiredGenerated, int maxDesiredGenerated)
{
for (int i = _children.Count - 1; i >= 0; i--)
{
GeneratorPosition childGeneratorPos = new GeneratorPosition(i, 0);
int itemIndex = _generator.IndexFromGeneratorPosition(childGeneratorPos);
if (itemIndex < minDesiredGenerated || itemIndex > maxDesiredGenerated)
{
//I don't much like this cast
// how do I access the IsSelectedProperty
// of a UIElement of any type ( ListBoxItem, TreeViewItem...)?
var c = _children[i] as ListViewItem;
c.IsEnabled = false;
if (c != null && c.IsSelected)
{
var layoutInfo = new Rect(0, 0, 0, 0);
c.Arrange(layoutInfo);
}
else
{
_generator.Remove(childGeneratorPos, 1);
RemoveInternalChildRange(i, 1);
}
}
}
}
In ArrangeOverride :
if (_children != null)
{
foreach (UIElement child in _children)
{
if (child.IsEnabled)
{
var layoutInfo = _realizedChildLayout[child];
child.Arrange(layoutInfo);
}
}
}
In MeasureOverride:
while (current < ItemsCount)
{
bool newlyRealized;
// Get or create the child
UIElement child = _generator.GenerateNext(out newlyRealized) as UIElement;
child.IsEnabled = true;
I'm still curious to know if there's a better way. In the meantime this will do.
btw I'll update the test project with this fix in case anyone wants a virtualizing wrappanel.

Making a AnimationQueue

I have been trying to make a Ellipse to follow a given trajectory with the DoubleAnimation class. So far not too good.
I made a custom class AnimationQueue :
private class AnimationQueue
{
private List<DoubleAnimation> animation1 ;
private DependencyProperty property1;
private bool running1;
private List<DoubleAnimation> animation2;
private DependencyProperty property2;
private bool running2;
private int curent;
private UIElement element;
public AnimationQueue(UIElement element , DependencyProperty property )
{
curent = -1;
this.element = element;
animation1 = new List<DoubleAnimation>();
animation2 = new List<DoubleAnimation>();
this.property1 = property;
}
public AnimationQueue(UIElement element, DependencyProperty property1 , DependencyProperty property2)
{
curent = -1;
this.element = element;
animation1 = new List<DoubleAnimation>();
animation2 = new List<DoubleAnimation>();
this.property1 = property1;
this.property2 = property2;
}
public void queueAnimation(DoubleAnimation animation1, DoubleAnimation animation2)
{
animation1.Completed += (s, e) =>
{
running1 = false;
};
animation2.Completed += (s, e) =>
{
running2 = false;
};
this.animation1.Add(animation1);
this.animation2.Add(animation2);
}
public void start(int i)
{
if (animation1.Count != animation2.Count)
Console.WriteLine("Animation Queue not equal");
else
{
if (i == animation1.Count)
Console.WriteLine("Animation finished");
else if (i <= animation1.Count && i <= animation2.Count)
{
element.BeginAnimation(property1, animation1[i]);
element.BeginAnimation(property2, animation2[i]);
if (running1 == false && running2 == false)
{
i++;
start(i);
}
}
}
}
public void start()
{
curent = 0;
element.BeginAnimation(property1, animation1[curent]);
element.BeginAnimation(property2, animation2[curent]);
if(running1 == false && running2 == false)
start(curent++);
}
}`
In this class I add 2 animations for each point in the coordinate list . 1 to animate the x axis movement and 1 to anymate the y axis movement . The adding goes like this :
public void StartCourse()
{
int i = 0;
List<Point> coordinates = course.firstFuntion();
while (coordinates.Count != i)
{
queue1.queueAnimation(new DoubleAnimation(coordinates[i].X, new Duration(TimeSpan.FromMilliseconds(500))),
new DoubleAnimation(coordinates[i].Y, new Duration(TimeSpan.FromMilliseconds(500)))
);
i++;
}
queue1.start();
}
My problem is , I believe , in the AnimationQueue.Start() method. The program stars the animation , however it only executes the first animation . After that it stops . I tried to make use of the animation.Completed Event Handler but to no success.
BeginAnimation starts animation asynchrously. I suppose this may help:
private class AnimationQueue
{
private List<DoubleAnimation> animation1 ;
private DependencyProperty property1;
private bool running1;
private List<DoubleAnimation> animation2;
private DependencyProperty property2;
private bool running2;
private int curent;
private UIElement element;
public AnimationQueue(UIElement element , DependencyProperty property )
{
curent = -1;
this.element = element;
animation1 = new List<DoubleAnimation>();
animation2 = new List<DoubleAnimation>();
this.property1 = property;
}
public AnimationQueue(UIElement element, DependencyProperty property1 , DependencyProperty property2)
{
curent = -1;
this.element = element;
animation1 = new List<DoubleAnimation>();
animation2 = new List<DoubleAnimation>();
this.property1 = property1;
this.property2 = property2;
}
public void queueAnimation(DoubleAnimation animation1, DoubleAnimation animation2)
{
this.animation1.Add(animation1);
this.animation2.Add(animation2);
animation1.Completed += (s, e) =>
{
if (this.animation1.Contains(animation1))
{
int index1 = this.animation1.IndexOf(animation1);
if (index1 + 1 < this.animation1.Count)
{
element.BeginAnimation(property1, animation1[index1 + 1]);
}
}
};
animation2.Completed += (s, e) =>
{
if (this.animation2.Contains(animation2))
{
int index2 = this.animation2.IndexOf(animation2);
if (index2 + 1 < this.animation2.Count)
{
element.BeginAnimation(property2, animation2[index2 + 1]);
}
}
};
}
public void start()
{
curent = 0;
element.BeginAnimation(property1, animation1[curent]);
element.BeginAnimation(property2, animation2[curent]);
}
}`

RadTileViewItem Drag/Drop in minimized state

I am using RadTileView in my project, and by default the Tile Drag and Drop is enabled when they are in restored state
,
but I can't achieve the same functionality when 1 tile is in maximized state and all others are in minimized state
,
I think that Telerik hasn't provided this functionality in their RadTileView control. What would be the best way to achieve this, or is it possible or not?
After searching through different blogs, I came to know that this functionality is not available in Telerik Tile view out of the box, but they have added it in their wish list, You can vote for this feature here http://www.telerik.com/support/pits.aspx#/public/silverlight/2449
However as a work arround I have implemented a Behavior my self for RadTileView, which will do the required task.
public class RadTilesDragDropBehavior : Behavior<RadTileView>
{
private RadTileViewItem draggingTile { get; set; }
public TileViewDragDropBehavior()
{
// Insert code required on object creation below this point.
}
protected override void OnAttached()
{
base.OnAttached();
// Insert code that you would want run when the Behavior is attached to an object.
DragDropManager.AddDragInitializeHandler(AssociatedObject, OnDragInitialize);
DragDropManager.AddDragDropCompletedHandler(AssociatedObject, OnDragAndDropCompleted);
AssociatedObject.PreviewDragOver += MyTileView_PreviewDragOver;
}
private void OnDragInitialize(object sender, DragInitializeEventArgs args)
{
var tileView = sender as RadTileView;
var tileViewItem = args.OriginalSource as RadTileViewItem;
Point pt = Util.CorrectGetPosition((RadTileView)sender);
HitTestResult result = VisualTreeHelper.HitTest(AssociatedObject, pt);
if (result != null)
{
DependencyObject obj = result.VisualHit.ParentOfType<RadFluidContentControl>();
if (obj != null)
{
//trying to drag from Tile content area, not allowed.
return;
}
}
if (tileViewItem != null && tileView != null && tileView.MaximizedItem != null)
{
args.Data = tileViewItem;
var draggingImage = new Image
{
Source = new Telerik.Windows.Media.Imaging.RadBitmap(tileViewItem).Bitmap,
Width = tileViewItem.RestoredWidth,
Height = tileViewItem.RestoredHeight
};
if (tileView.MaximizedItem == tileViewItem)
{
args.DragVisualOffset = new Point(args.RelativeStartPoint.X - 50, args.RelativeStartPoint.Y-55);
}
args.DragVisual = draggingImage;
tileViewItem.Opacity = 0;
args.AllowedEffects = DragDropEffects.Move;
args.Handled = true;
// keep a copy of dragging tile
draggingTile = tileViewItem;
}
}
private void OnDragAndDropCompleted(object sender, DragDropCompletedEventArgs args)
{
if (args.OriginalSource.GetType() == typeof(RadTileViewItem))
{
if (AssociatedObject.MaximizedItem != null)
{
Point pt = Util.CorrectGetPosition((RadTileView)sender);
HitTestResult result = VisualTreeHelper.HitTest(AssociatedObject, pt);
if (result != null)
{
DependencyObject obj = result.VisualHit.ParentOfType<RadTileViewItem>();
if (obj != null)
{
((RadTileViewItem)obj).Position = draggingTile.Position;
draggingTile.Opacity = 100;
}
else
{
draggingTile.Opacity = 100;
}
}
else
{
draggingTile.Opacity = 100;
}
}
}
}
private void MyTileView_PreviewDragOver(object sender, System.Windows.DragEventArgs e)
{
FrameworkElement container = sender as FrameworkElement;
if (AssociatedObject.MaximizedItem != null)
{
if (container == null)
{
return;
}
double tolerance = 60;
double verticalPos = Util.CorrectGetPosition((RadTileView)container).Y;
double offset = 20;
ScrollViewer scrollViewer = AssociatedObject.FindChildByType<ScrollViewer>();
if (verticalPos < tolerance) // Top of visible list?
{
scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - offset); //Scroll up.
}
else if (verticalPos > container.ActualHeight - tolerance) //Bottom of visible list?
{
scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset + offset); //Scroll down.
}
}
}
protected override void OnDetaching()
{
base.OnDetaching();
// Insert code that you would want run when the Behavior is removed from an object.
DragDropManager.RemoveDragInitializeHandler(AssociatedObject, OnDragInitialize);
DragDropManager.RemoveDragDropCompletedHandler(AssociatedObject, OnDragAndDropCompleted);
AssociatedObject.PreviewDragOver -= MyTileView_PreviewDragOver;
}
}
public static class Util
{
public static Point CorrectGetPosition(Visual relativeTo)
{
Win32Point w32Mouse = new Win32Point();
GetCursorPos(ref w32Mouse);
return relativeTo.PointFromScreen(new Point(w32Mouse.X, w32Mouse.Y));
}
[StructLayout(LayoutKind.Sequential)]
internal struct Win32Point
{
public Int32 X;
public Int32 Y;
};
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetCursorPos(ref Win32Point pt);
};
XAML would be like this
<telerik:RadTileView x:Name="MyTileView" ItemsSource={Binding TileItems}>
<i:Interaction.Behaviors>
<behaviors:RadTilesDragDropBehavior/>
</i:Interaction.Behaviors>
</telerik:RadTileView>

Polyline bound to ObservableList<Point> doesn't refresh

I have a class (let's call it externalClass) with a ObservableCollection<Point> channel1 inside. (the class itself does NOT implements INotify)
In the MainWindow I have a polyline binded to this externalClass.channel1 that uses a converter from ObservableCollection to PointCollection.
So from the C# I bind DataContext = externalClass; and in the XAML the polyline looks like:
<Polyline Points="{Binding channel1, Converter={StaticResource pointCollectionConverter}}" Stroke="#FF00E100" Name="line" />
I have a test function that works like that:
public void test()
{
ObservableCollection<Point> newone = new ObservableCollection<Point>();
for (int i = 0; i < debugCh1.Count; i++)
{
Point p1 = debugCh1[i];
p1.Y = p1.Y + 1;
newone.Add(p1);
}
channel1= newone;
}
If I add a breakpoint in the converter itself I can see that on start-up it is called (and actually the initial values (hard-coded) are displayed. But when I add the test function to a button .. it does nothing (the converter is not called)
Any idea idea of where the notification of the changes is being stopped ???
SOLUTION
After reading the answers and googleling a bit more I came out with the soulition. Id like to post it there for everybody else
So .. The so-called externalClass must inherit from INotifyPropertyChanged and it must implement NotifyPropertyChanged
So all and all it must be declared like that:
public class externalClass : INotifyPropertyChanged
{
....
// at some point you have your ObservableCollection<smth> as a property
public ObservableCollection<Point> channel1 { get; set; }
....
//at some point you implement NotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string caller)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(caller));
}
}
....
//then whenever you need to fire the notification
[..]do something with channel1
NotifyPropertyChanged("channel1");
And that's all. If you add a proper binding (as the one I showed in my question) the whole set up is gonna work.. At least mine worked hehehe
Good luck! And thanks to the people that helped me !! :D
Polyline Points probably does not listen to INotifyCollectionChanged when bound. Try exposing Channel1 as a property and raise the INotifyPropertyChanged with "Channel1"
First, you need create your custom class PointCollection:
public class PointCollection : ObservableCollection<Point>
{
public PointCollection()
{
}
public PointCollection(IEnumerable<Point> points) : base(points)
{
}
}
Second, you need create custom Polyline:
public class PolylineDynamic : Shape
{
private Geometry _polylineGeometry = Geometry.Empty;
public static readonly DependencyProperty PointsProperty = DependencyProperty.Register(nameof(Points), typeof(PointCollection), typeof(PolylineDynamic), new FrameworkPropertyMetadata(PointsChanged));
private static void PointsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((PolylineDynamic)d).PointsChanged(e);
}
private void PointsChanged(DependencyPropertyChangedEventArgs e)
{
if (e.OldValue is PointCollection oldPoints)
oldPoints.CollectionChanged -= OnPointsChanged;
if (e.NewValue is PointCollection newPoints)
newPoints.CollectionChanged += OnPointsChanged;
UpdatePolyline();
}
public PointCollection Points
{
get => (PointCollection)GetValue(PointsProperty);
set => SetValue(PointsProperty, value);
}
public static readonly DependencyProperty FillRuleProperty = DependencyProperty.Register(nameof(FillRule), typeof(FillRule), typeof(PolylineDynamic), new FrameworkPropertyMetadata(FillRule.EvenOdd));
public FillRule FillRule
{
get => (FillRule)GetValue(FillRuleProperty);
set => SetValue(FillRuleProperty, value);
}
protected override Geometry DefiningGeometry => _polylineGeometry;
private void OnPointsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
var aPoint = e.NewItems.OfType<Point>().Single();
Add(aPoint, e.NewStartingIndex);
break;
case NotifyCollectionChangedAction.Remove:
Remove(e.OldStartingIndex);
break;
case NotifyCollectionChangedAction.Replace:
var rPoint = e.NewItems.OfType<Point>().Single();
Replace(rPoint, e.NewStartingIndex);
break;
}
}
protected void UpdatePolyline()
{
if (Points == null || Points.Count < 2)
_polylineGeometry = Geometry.Empty;
else
{
var pGeometry = GetPathGeometry();
for (var i = 0; i < Points.Count; i++)
{
if (i == 0)
continue;
var startPoint = Points[i - 1];
var point = Points[i];
var figure = new PathFigure { StartPoint = startPoint };
figure.Segments.Add(new LineSegment(point, true));
pGeometry.Figures.Add(figure);
}
}
}
private void Add(Point point, int index)
{
var pGeometry = GetPathGeometry();
if (pGeometry.Figures.Count == 0)
{
UpdatePolyline();
return;
}
if (index == Points.Count - 1)
{
var segment = new LineSegment(point, true);
var figure = new PathFigure { StartPoint = Points[index - 1] };
figure.Segments.Add(segment);
pGeometry.Figures.Add(figure);
}
else if (index == 0)
{
var segment = new LineSegment(Points[1], true);
var figure = new PathFigure { StartPoint = point };
figure.Segments.Add(segment);
pGeometry.Figures.Insert(0, figure);
}
else
{
var leftFigure = new PathFigure { StartPoint = Points[index - 1] };
leftFigure.Segments.Add(new LineSegment(point, true));
var rightFigure = new PathFigure { StartPoint = point };
rightFigure.Segments.Add(new LineSegment(Points[index + 1], true));
pGeometry.Figures.Insert(index - 1, leftFigure);
pGeometry.Figures.Insert(index, rightFigure);
}
InvalidateVisual();
}
private void Remove(int index)
{
var pGeometry = GetPathGeometry();
if (!pGeometry.Figures.Any())
{
_polylineGeometry = Geometry.Empty;
InvalidateVisual();
return;
}
if (index == Points.Count - 1 || index == 0)
pGeometry.Figures.RemoveAt(index);
else
{
var leftFigure = pGeometry.Figures[index - 1];
var rightFigure = pGeometry.Figures[index];
pGeometry.Figures.RemoveAt(index - 1);
rightFigure.StartPoint = ((LineSegment)leftFigure.Segments.Single()).Point;
}
InvalidateVisual();
}
private void Replace(Point point, int index)
{
var pGeometry = GetPathGeometry();
if (index == 0)
pGeometry.Figures[0].StartPoint = point;
else if (index == Points.Count - 1)
ReplaceSegment(pGeometry.Figures[index - 1], point);
else
{
ReplaceSegment(pGeometry.Figures[index - 1], point);
pGeometry.Figures[index].StartPoint = point;
}
InvalidateVisual();
}
private void ReplaceSegment(PathFigure figure, Point point)
{
figure.Segments.Clear();
figure.Segments.Add(new LineSegment(point, true));
}
private PathGeometry GetPathGeometry()
{
if (_polylineGeometry is PathGeometry pathGeometry)
return pathGeometry;
else
{
pathGeometry = new PathGeometry { FillRule = FillRule };
_polylineGeometry = pathGeometry;
return pathGeometry;
}
}
}
If you need more functionality, you can add more)

Resources