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.
I have a requirement in WPF in which...
I want Rich text box to be used as dateTemplate for a listview for one particular column(which has remarks)
I have set of key word (add, search, location etc..)
In that column I want all those keywords to be highlighted in yellow colour.
I have another TextBox .If I type any word for searching in that text box and it exists in listview then it should be highlighted with green.
If I search the keyword which are in yellow then they should not be highlighted with green they should be in yellow colour.
If I have “added” word in which add is highlighted in yellow then when I search for “added” “add” should be in yellow and “ed” should be in green.
Any help is appreciated. I have tried several ways but failed at the last point above.
//Code snippet
// Xaml File
<Window x:Class="RichtextBoxhighlight.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:RichtextBoxhighlight"
Title="MainWindow" Height="406" Width="855"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Window.Resources>
<src:ContentPlainConverter x:Key="typeConverter" />
<src:TestConvertor x:Key="spaceRem"/>
<Style x:Key="RichTextBoxWithRoundedCorners" TargetType="{x:Type RichTextBox}">
<Style.Resources>
<Style x:Key="{x:Type FlowDocument}" TargetType="{x:Type FlowDocument}">
<Setter Property="OverridesDefaultStyle" Value="true"/>
</Style>
</Style.Resources>
</Style>
</Window.Resources>
<Grid>
<TextBox Margin="114,14,130,255" Name="txtText" />
<Grid>
<ListView Height="241" ItemsSource="{Binding CollRemarks}" HorizontalAlignment="Left" Margin="0,126,0,0" Name="listView1" VerticalAlignment="Top" Width="827" >
<ListView.View >
<GridView >
<GridViewColumn Header="Type" Width="80" DisplayMemberBinding="{Binding Path=type}"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Operatorid}" Width="70">
<GridViewColumnHeader Tag="CreatedEmployeeId" Content="Operator"/>
</GridViewColumn>
<GridViewColumn Width="710">
<GridViewColumn.CellTemplate>
<DataTemplate>
<src:BindableRichTextBox Document ="{Binding Path=remarks, Converter= {StaticResource typeConverter}}" HighlightPhrase="{Binding ElementName=txtText, Path=Text,Converter={StaticResource spaceRem}}" IsReadOnly="True" Background="Transparent" BorderBrush="Transparent" BorderThickness="0"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
<GridViewColumnHeader Tag="CommentText" Content="Remark" />
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Grid>
</Window>
//BindableRichTextBox class :
namespace RichtextBoxhighlight
{
public class BindableRichTextBox : RichTextBox
{
public static string oldstring;
public static readonly DependencyProperty DocumentProperty =
DependencyProperty.Register("Document", typeof(FlowDocument),
typeof(BindableRichTextBox), new FrameworkPropertyMetadata
(null, new PropertyChangedCallback(OnDocumentChanged)));
public static readonly DependencyProperty HighlightPhraseProperty =
DependencyProperty.Register("HighlightPhrase", typeof(string),
typeof(BindableRichTextBox), new FrameworkPropertyMetadata(String.Empty, FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(UpdateHighlighting)));
public string HighlightPhrase
{
get { return (string)GetValue(HighlightPhraseProperty); }
set { SetValue(HighlightPhraseProperty, value); }
}
private static void UpdateHighlighting(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
//invoked on text box search
ApplyHighlight(d as BindableRichTextBox);
ApplyAllHighlight(d as BindableRichTextBox);
}
// Gets or sets the Document of RichtextBox
public new FlowDocument Document
{
get
{
return (FlowDocument)this.GetValue(DocumentProperty);
}
set
{
this.SetValue(DocumentProperty, value);
}
}
// Method invoked on documnet formation.
public static void OnDocumentChanged(DependencyObject obj,
DependencyPropertyChangedEventArgs args)
{
try
{
RichTextBox rtb = (RichTextBox)obj;
// ApplyHighlight(rtb as BindableRichTextBox);
rtb.Document = (FlowDocument)args.NewValue;
ApplyAllHighlight(rtb as BindableRichTextBox);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// Implementation logic for Text Changed search highlight
/// </summary>
private static void ApplyHighlight(BindableRichTextBox tb)
{
try
{
if (tb != null && tb.Document != null)
{
string highlightPhrase = tb.HighlightPhrase;
// Frame the highlight word to skip them from getting highlighted by searchtext
string highlightWords = "(";
for (int i = 0; i < MainWindow.Highlightwords.Count; i++)
{
highlightWords += MainWindow.Highlightwords[i];
if (i != MainWindow.Highlightwords.Count - 1)
highlightWords += "|";
}
highlightWords += ")";
var start = tb.Document.ContentStart;
TextRange range = new TextRange(start, tb.Document.ContentEnd);
range.ClearAllProperties();
Regex ignore = new Regex(highlightWords, RegexOptions.Compiled | RegexOptions.IgnoreCase);
string Text = range.Text;
int index_match = 0;
if (highlightPhrase != string.Empty && highlightPhrase != null)
{
while (start != null && start.CompareTo(tb.Document.ContentEnd) < 0)
{
// Comparison to skip the key words in the column to be highlighted
if (start.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
{
index_match = Text.IndexOf(highlightPhrase, StringComparison.OrdinalIgnoreCase);
if (index_match >= 0)
{
//Ignore all Keyword highlight by incrementing start and moving to next match
MatchCollection matches = ignore.Matches(start.GetTextInRun(LogicalDirection.Forward));
if (matches != null)
{
for (int i = 0; i < matches.Count; i++)
{
if ((index_match >= matches[i].Index && index_match <= matches[i].Index + matches[i].Length))
{
start = start.GetPositionAtOffset(matches[i].Index + matches[i].Length, LogicalDirection.Forward);
Text = new TextRange(start.GetInsertionPosition(LogicalDirection.Forward), start.DocumentEnd).Text;
//Highlight the search text if part before keyword
if (highlightPhrase.Length > matches[i].Length)
{
var textrange = new TextRange(start.GetPositionAtOffset(0, LogicalDirection.Forward), start.GetPositionAtOffset(highlightPhrase.Length - matches[i].Length, LogicalDirection.Backward));
textrange.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Green));
}
if (start != null && start.CompareTo(tb.Document.ContentEnd) < 0)
{
index_match = Text.IndexOf(highlightPhrase, StringComparison.OrdinalIgnoreCase);
if (index_match >= 0)
{
matches = ignore.Matches(start.GetTextInRun(LogicalDirection.Forward));
if (matches != null && matches.Count > 0)
i--;
}
else
break;
}
}
else if ((highlightPhrase.Length - 1 >= matches[i].Index && highlightPhrase.Length + index_match <= matches[i].Index + matches[i].Length))
{
//Highlight the search text if part after keyword
var textrange = new TextRange(start.GetPositionAtOffset(index_match, LogicalDirection.Forward), start.GetPositionAtOffset(matches[i].Index, LogicalDirection.Backward));
textrange.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Green));
start = start.GetPositionAtOffset(matches[i].Index + matches[i].Length, LogicalDirection.Forward);
Text = new TextRange(start.GetInsertionPosition(LogicalDirection.Forward), start.DocumentEnd).Text;
if (start != null && start.CompareTo(tb.Document.ContentEnd) < 0)
{
index_match = Text.IndexOf(highlightPhrase, StringComparison.OrdinalIgnoreCase);
if (index_match >= 0)
{
matches = ignore.Matches(start.GetTextInRun(LogicalDirection.Forward));
if (matches != null && matches.Count > 0)
i--;
}
else
break;
}
}
}
}
if (index_match >= 0 && start != null && (start.CompareTo(tb.Document.ContentEnd) < 0))
{
//Highlight the search text typed if not part of Keywords
var textrange = new TextRange(start.GetPositionAtOffset(index_match, LogicalDirection.Forward), start.GetPositionAtOffset(index_match + highlightPhrase.Length, LogicalDirection.Backward));
textrange.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Green));
start = textrange.End;
Text = new TextRange(textrange.End, start.DocumentEnd).Text;
}
}
else
break;
}
if (start != null && start.CompareTo(tb.Document.ContentEnd) < 0)
start = start.GetNextContextPosition(LogicalDirection.Forward);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// Implementation logic for key words highlight
/// </summary>
private static void ApplyAllHighlight(BindableRichTextBox rtb)
{
try
{
if (rtb != null)
{
string highlightWords = "(";
for (int i = 0; i < MainWindow.Highlightwords.Count; i++)
{
highlightWords += MainWindow.Highlightwords[i];
if (i != MainWindow.Highlightwords.Count - 1)
highlightWords += "|";
}
highlightWords += ")";
Regex reg = new Regex(highlightWords, RegexOptions.Compiled | RegexOptions.IgnoreCase);
var start = rtb.Document.ContentStart;
while (start != null && start.CompareTo(rtb.Document.ContentEnd) < 0)
{
if (start.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
{
var match = reg.Match(start.GetTextInRun(LogicalDirection.Forward));
var textrange = new TextRange(start.GetPositionAtOffset(match.Index, LogicalDirection.Forward), start.GetPositionAtOffset(match.Index + match.Length, LogicalDirection.Backward));
textrange.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Yellow));
start = textrange.End;
}
start = start.GetNextContextPosition(LogicalDirection.Forward);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
//Content of list view remarks column and keywords to be highlighted
//Key word to be highlighted
Highlightwords = new List<string>();
Highlightwords.Add("mment");
Highlightwords.Add("ADD");
Highlightwords.Add("LOCATION");
Highlightwords.Add("arch");
// Remarks in list view
CollRemarks = new ObservableCollection<evcom>();
string remar = "search for added comments in location added";
CollRemarks.Add(new evcom { type = "Info", Operatorid = "1728", remarks = remar });
remar = "searched for added add comments in location added LOCATIONS";
CollRemarks.Add(new evcom { type = "Info", Operatorid = "1783", remarks = remar });
I have some paths drawn to the screen in wpf. The coordinates being used are quite small so they have been made to fill the screen with a view box. I am now trying to implement pan and zoom functionality. I would like to be able to zoom to wherever the mouse is in relation to the ui (i.e zoomed screen center is equal to mouse coordinates). The current outcome is that the center of the screen when zoomed is not reflective of the exact mouse position on the ui.
If you want to see what is happening... Here is my current solution file.
Or
Heres some code:
View Xaml
<Grid Name="MasterGrid" DataContext="{StaticResource mainWindowViewModel}">
<ScrollViewer HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible" Name="VisualisationScroller">
<Viewbox Name="VisualisationBox" Stretch="Fill" Loaded="VisualisationBox_Loaded">
<ItemsControl Name="CustomDrawingElement" ItemsSource="{Binding Trajectories}" Width="{Binding VisualisationWidth}" Height="{Binding VisualisationHeight}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="data:VisualisedTrajectory">
<Path Data = "{Binding PathData}" Stroke="Red" StrokeThickness="0.001" Fill="Transparent" />
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas
Background="DarkGray"
IsItemsHost="True">
</Canvas>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="1" ScaleY="1" />
<TranslateTransform />
</TransformGroup>
</ItemsControl.RenderTransform>
</ItemsControl>
</Viewbox>
</ScrollViewer>
</Grid>
View Model
public class MainWindowViewModel : BaseViewModel
{
public MainWindowViewModel()
{
VisualiseRawTrajectories();
}
private ObservableCollection<VisualisedTrajectory> _trajectories = new ObservableCollection<VisualisedTrajectory>();
public ObservableCollection<VisualisedTrajectory> Trajectories
{
get { return _trajectories; }
}
#region VisualisationDimensions
private double _visualisationWidth = 100;
public double VisualisationWidth
{
get { return _visualisationWidth; }
private set { _visualisationWidth = value; }
}
private double _visualisationHeight = 100;
public double VisualisationHeight
{
get { return _visualisationHeight; }
private set { _visualisationHeight = value; }
}
#endregion
public void VisualiseRawTrajectories()
{
var rand = new Random();
for (int i = 0; i < 5; i++)
{
var currentTrajectorySet = new List<Point>(); //each time through reinitialise
for (int j = 0; j < 5; j++)
{
currentTrajectorySet.Add(new Point(rand.NextDouble() * 0.5, rand.NextDouble() * 0.5)); //add a new point with max 0.5
if(j == 4)
{
currentTrajectorySet.Add(new Point(0.5, 0.5)); //for good measure :)
_trajectories.Add(new VisualisedTrajectory(CreatePathData(currentTrajectorySet)));
}
}
}
VisualisationHeight = 0.5;
VisualisationWidth = 0.5; //just for demonstration purposes
OnPropertyChanged("VisualisationHeight");
OnPropertyChanged("VisualisationWidth");
}
private Geometry CreatePathData(IList<Point> points)
{
var geometry = new StreamGeometry {FillRule = FillRule.EvenOdd};
using (StreamGeometryContext ctx = geometry.Open())
{
ctx.BeginFigure(points[0], false, false); //use the first index
ctx.PolyLineTo(points, true, true);
}
return (Geometry)geometry.GetAsFrozen();
}
}
View Code Behind
public MainWindow()
{
InitializeComponent();
VisualisationScroller.PreviewMouseWheel += OnPreviewMouseWheel;
}
private Point originalDimensions;
private void VisualisationBox_Loaded(object sender, RoutedEventArgs e)
{
Viewbox viewBox = sender as Viewbox;
viewBox.Width = viewBox.ActualWidth;
viewBox.Height = viewBox.ActualHeight;
originalDimensions = new Point(viewBox.ActualWidth, viewBox.ActualHeight);
}
#region Zoom
private int _numberDrawnItems = 0;
private void OnPreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
var zoomScale = new Point(CustomDrawingElement.RenderTransform.Value.M11,
CustomDrawingElement.RenderTransform.Value.M22); //gets the scale x and scale y
if (CustomDrawingElement != null && _numberDrawnItems != CustomDrawingElement.Items.Count) //if there was something draw to screen
{
_numberDrawnItems = CustomDrawingElement.Items.Count;
CustomDrawingElement.RenderTransformOrigin = new Point(0.5, 0.5); //if not set zoom from center
}
if (e.Delta > 0)
{
if (CustomDrawingElement != null)
{
VisualisationBox.Width = originalDimensions.X * (zoomScale.X + 1);
VisualisationBox.Height = originalDimensions.Y * (zoomScale.Y + 1);
var mousePosition = e.GetPosition(MasterGrid);
CustomDrawingElement.RenderTransformOrigin = new Point(mousePosition.X / MasterGrid.ActualWidth, mousePosition.Y / MasterGrid.ActualHeight);
CustomDrawingElement.RenderTransform = new MatrixTransform(zoomScale.X + 1, 0, 0, zoomScale.Y + 1, 0, 0);
}
}
if (e.Delta < 0)
{
if (zoomScale.X > 1 && zoomScale.Y > 1) //stops you from zooming out too much
{
if (CustomDrawingElement != null)
{
VisualisationBox.Width = VisualisationBox.Width - originalDimensions.X;
VisualisationBox.Height = VisualisationBox.Height - originalDimensions.Y;
CustomDrawingElement.RenderTransform = new MatrixTransform(zoomScale.X - 1, 0, 0, zoomScale.Y - 1, 0, 0);
}
}
}
e.Handled = true;
}
#endregion //Zooming code
}
Solved it changed the back code for zooming the View to:
if (e.Delta > 0)
{
if (CustomDrawingElement != null)
{
//zoom
_zoomScale++; //increase it now that we have zoomed
VisualisationBox.Width = _originalDimensions.X * (_zoomScale);
VisualisationBox.Height = _originalDimensions.Y * (_zoomScale);
ScrollerDimensions.Content = VisualisationScroller.ActualWidth + "x" + VisualisationScroller.ActualHeight;
BoxDimensions.Content = VisualisationBox.ActualWidth + "x" + VisualisationBox.ActualHeight;
var mousePosition = e.GetPosition(MasterGrid);
mousePosition = MasterGrid.TransformToVisual(VisualisationBox).Transform(mousePosition);
ScrolledPoint.Content = mousePosition.X + "," + mousePosition.Y;
VisualisationScroller.ScrollToHorizontalOffset(mousePosition.X);
VisualisationScroller.ScrollToVerticalOffset(mousePosition.Y);
}
}
if (e.Delta < 0)
{
if (_zoomScale > 1) //stops you from zooming out too much
{
if (CustomDrawingElement != null)
{
var mousePosition = e.GetPosition(MasterGrid);
_zoomScale -= 1; //decrease the zoom
VisualisationBox.Width = VisualisationBox.Width - _originalDimensions.X;
VisualisationBox.Height = VisualisationBox.Height - _originalDimensions.Y;
mousePosition = MasterGrid.TransformToVisual(VisualisationBox).Transform(mousePosition);
mousePosition = new Point(mousePosition.X - _originalDimensions.X, mousePosition.Y - _originalDimensions.Y);
VisualisationScroller.ScrollToHorizontalOffset(mousePosition.X);
VisualisationScroller.ScrollToVerticalOffset(mousePosition.Y);
}
}
}
e.Handled = true;
If anyone is interested HERE is the finished solution file with panning implemented too.
I have an ItemsControl and I want the data to be entered into two columns. When the User resizes to a width lesser than the second column, the items of the second column must wrap into the first column. Something like a UniformGrid but with wrapping.
I have managed to use a WrapPanel to do this. But I am forced to manipulate and hard code the ItemWidth and MaxWidth of the WrapPanel to achieve the two columns thing and the wrapping. This is not a good practice.
Is there anyway to set the Maximum no of columns or in other words allowing us to decide at what point the WrapPanel should start wrapping?
Some browsing on the internet revealed that the WrapGrid in Windows 8 Metro has this property. Does anyone have this implementation in WPF?
There's an UniformWrapPanel article on codeproject.com, which I modified to ensure the items in a wrap panel have uniform width and fit to the width of the window. You should easily be able to modify this code to have a maximum number of columns. Try changing the code near
var itemsPerRow = (int) (totalWidth/ItemWidth);
in order to specify the max columns.
Here's the code:
public enum ItemSize
{
None,
Uniform,
UniformStretchToFit
}
public class UniformWrapPanel : WrapPanel
{
public static readonly DependencyProperty ItemSizeProperty =
DependencyProperty.Register(
"ItemSize",
typeof (ItemSize),
typeof (UniformWrapPanel),
new FrameworkPropertyMetadata(
default(ItemSize),
FrameworkPropertyMetadataOptions.AffectsMeasure,
ItemSizeChanged));
private static void ItemSizeChanged(
DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var uniformWrapPanel = sender as UniformWrapPanel;
if (uniformWrapPanel != null)
{
if (uniformWrapPanel.Orientation == Orientation.Horizontal)
{
uniformWrapPanel.ItemWidth = double.NaN;
}
else
{
uniformWrapPanel.ItemHeight = double.NaN;
}
}
}
public ItemSize ItemSize
{
get { return (ItemSize) GetValue(ItemSizeProperty); }
set { SetValue(ItemSizeProperty, value); }
}
protected override Size MeasureOverride(Size availableSize)
{
var mode = ItemSize;
if (Children.Count > 0 && mode != ItemSize.None)
{
bool stretchToFit = mode == ItemSize.UniformStretchToFit;
if (Orientation == Orientation.Horizontal)
{
double totalWidth = availableSize.Width;
ItemWidth = 0.0;
foreach (UIElement el in Children)
{
el.Measure(availableSize);
Size next = el.DesiredSize;
if (!(Double.IsInfinity(next.Width) || Double.IsNaN(next.Width)))
{
ItemWidth = Math.Max(next.Width, ItemWidth);
}
}
if (stretchToFit)
{
if (!double.IsNaN(ItemWidth) && !double.IsInfinity(ItemWidth) && ItemWidth > 0)
{
var itemsPerRow = (int) (totalWidth/ItemWidth);
if (itemsPerRow > 0)
{
ItemWidth = totalWidth/itemsPerRow;
}
}
}
}
else
{
double totalHeight = availableSize.Height;
ItemHeight = 0.0;
foreach (UIElement el in Children)
{
el.Measure(availableSize);
Size next = el.DesiredSize;
if (!(Double.IsInfinity(next.Height) || Double.IsNaN(next.Height)))
{
ItemHeight = Math.Max(next.Height, ItemHeight);
}
}
if (stretchToFit)
{
if (!double.IsNaN(ItemHeight) && !double.IsInfinity(ItemHeight) && ItemHeight > 0)
{
var itemsPerColumn = (int) (totalHeight/ItemHeight);
if (itemsPerColumn > 0)
{
ItemHeight = totalHeight/itemsPerColumn;
}
}
}
}
}
return base.MeasureOverride(availableSize);
}
}
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);
}