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:
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>
I'm writing a user control for animation.
Its uses an internal ImageList to store the animation images and paint one after the other in a loop.
This is the whole code:
public partial class Animator : UserControl
{
public event EventHandler OnLoopElapsed = delegate { };
private ImageList imageList = new ImageList();
private Timer timer;
private bool looping = true;
private int index;
private Image newImage;
private Image oldImage;
public Animator()
{
InitializeComponent();
base.DoubleBuffered = true;
timer = new Timer();
timer.Tick += timer_Tick;
timer.Interval = 50;
}
public bool Animate
{
get { return timer.Enabled; }
set
{
index = 0;
timer.Enabled = value;
}
}
public int CurrentIndex
{
get { return index; }
set { index = value; }
}
public ImageList ImageList
{
set
{
imageList = value;
Invalidate();
index = 0;
}
get { return imageList; }
}
public bool Looping
{
get { return looping; }
set { looping = value; }
}
public int Interval
{
get { return timer.Interval; }
set { timer.Interval = value; }
}
private void timer_Tick(object sender, EventArgs e)
{
if (imageList.Images.Count == 0)
return;
Invalidate(true);
index++;
if (index >= imageList.Images.Count)
{
if (looping)
index = 0;
else
timer.Stop();
OnLoopElapsed(this, EventArgs.Empty);
}
}
protected override void OnPaintBackground(PaintEventArgs e)
{
if (oldImage != null)
e.Graphics.DrawImage(oldImage, ClientRectangle);
else
e.Graphics.Clear(BackColor);
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
if (imageList.Images.Count > 0)
{
newImage = imageList.Images[index];
g.DrawImage(newImage, ClientRectangle);
oldImage = newImage;
}
else
{
e.Graphics.Clear(BackColor);
}
}
}
The animation seems very nice and smooth,
but the problem is that its surrounding rectangle is painted black.
What am I missing here?
I've seen very smooth transparent animation done here in WPF,
I've placed some label behind it and they are seen thru the rotating wheel as I hoped.
But I don't know WPF well enough to build such a control in WPF.
Any idea or WPF sample code will be appreciated.
This was solved by removing this line from the constructor:
base.DoubleBuffered = true;
Now the control is fully transparent, even while changing its images.
CompositeTransform is only used for silverlight?. Is there anyway we can use that in WPF or any equivalent replacement?
There is no CompositeTransform in WPF however there is a TransformGroup. Hence an equivalent replacement is a TransformGroup containing ScaleTransform, SkewTransform, RotateTransform and TranslateTransform in that order.
Here is a much nicer solution if you are anal about code cleanliness:
http://www.singulink.com/CodeIndex/post/getting-rid-of-ugly-transformgroup-blocks-in-wpf
Its easy on the eyes and because it just returns a TransformGroup, you can still use the Blend designer to work with animating over the transform!
<Rectangle Width="100" Height="100" Fill="LightGreen"
RenderTransform="{data:CompositeTransform ScaleX=2.5, ScaleY=1, SkewX=-60, Rotation=145}"
RenderTransformOrigin="0.5,0.5" />
Implementation:
public class CompositeTransformExtension : MarkupExtension
{
public double CenterX
{
get { return _scale.CenterX; }
set
{
_scale.CenterX = value;
_skew.CenterX = value;
_rotate.CenterX = value;
}
}
public double CenterY
{
get { return _scale.CenterY; }
set
{
_scale.CenterY = value;
_skew.CenterY = value;
_rotate.CenterY = value;
}
}
public double ScaleX
{
get { return _scale.ScaleX; }
set { _scale.ScaleX = value; }
}
public double ScaleY
{
get { return _scale.ScaleY; }
set { _scale.ScaleY = value; }
}
public double SkewX
{
get { return _skew.AngleX; }
set { _skew.AngleX = value; }
}
public double SkewY
{
get { return _skew.AngleY; }
set { _skew.AngleY = value; }
}
public double Rotation
{
get { return _rotate.Angle; }
set { _rotate.Angle = value; }
}
public double TranslateX
{
get { return _translate.X; }
set { _translate.X = value; }
}
public double TranslateY
{
get { return _translate.Y; }
set { _translate.Y = value; }
}
private ScaleTransform _scale = new ScaleTransform();
private SkewTransform _skew = new SkewTransform();
private RotateTransform _rotate = new RotateTransform();
private TranslateTransform _translate = new TranslateTransform();
public CompositeTransformExtension()
{
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
var group = new TransformGroup();
group.Children.Add(_scale);
group.Children.Add(_skew);
group.Children.Add(_rotate);
group.Children.Add(_translate);
return group;
}
}
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);
}