Snapping a SurfaceListBox - wpf

I'm looking to create a scrolling surfacelistbox which automatically snaps into a position after a drag is finished so that the center item on the screen is centered itself in the viewport.
I've gotten the center item, but now as usual the way that WPF deals with sizes, screen positions, and offsets has me perplexed.
At the moment I've chosen to subscribe to the SurfaceScrollViewer's ManipulationCompleted event, as that seems to consistently fire after I've finished a scroll gesture (whereas the ScrollChanged event tends to fire early).
void ManipCompleted(object sender, ManipulationCompletedEventArgs e)
{
FocusTaker.Focus(); //reset focus to a dummy element
List<FrameworkElement> visibleElements = new List<FrameworkElement>();
for (int i = 0; i < List.Items.Count; i++)
{
SurfaceListBoxItem item = List.ItemContainerGenerator.ContainerFromIndex(i) as SurfaceListBoxItem;
if (ViewportHelper.IsInViewport(item) && (List.Items[i] as string != "Dummy"))
{
FrameworkElement el = item as FrameworkElement;
visibleElements.Add(el);
}
}
int centerItemIdx = visibleElements.Count / 2;
FrameworkElement centerItem = visibleElements[centerItemIdx];
double center = ss.ViewportWidth / 2;
//ss is the SurfaceScrollViewer
Point itemPosition = centerItem.TransformToAncestor(ss).Transform(new Point(0, 0));
double desiredOffset = ss.HorizontalOffset + (center - itemPosition.X);
ss.ScrollToHorizontalOffset(desiredOffset);
centerItem.Focus(); //this also doesn't seem to work, but whatever.
}
The list snaps, but where it snaps seems to be somewhat chaotic. I have a line down the center of the screen, and sometimes it looks right down the middle of the item, but other times it's off to the side or even between items. Can't quite nail it down, but it seems that the first and fourth quartile of the list work well, but the second and third are progressively more off toward the center.
Just looking for some help on how to use positioning in WPF. All of the relativity and the difference between percentage-based coordinates and 'screen-unit' coordinates has me somewhat confused at this point.

After a lot of trial and error I ended up with this:
void ManipCompleted(object sender, ManipulationCompletedEventArgs e)
{
FocusTaker.Focus(); //reset focus
List<FrameworkElement> visibleElements = new List<FrameworkElement>();
for (int i = 0; i < List.Items.Count; i++)
{
SurfaceListBoxItem item = List.ItemContainerGenerator.ContainerFromIndex(i) as SurfaceListBoxItem;
if (ViewportHelper.IsInViewport(item))
{
FrameworkElement el = item as FrameworkElement;
visibleElements.Add(el);
}
}
Window window = Window.GetWindow(this);
double center = ss.ViewportWidth / 2;
double closestCenterOffset = double.MaxValue;
FrameworkElement centerItem = visibleElements[0];
foreach (FrameworkElement el in visibleElements)
{
double centerOffset = Math.Abs(el.TransformToAncestor(window).Transform(new Point(0, 0)).X + (el.ActualWidth / 2) - center);
if (centerOffset < closestCenterOffset)
{
closestCenterOffset = centerOffset;
centerItem = el;
}
}
Point itemPosition = centerItem.TransformToAncestor(window).Transform(new Point(0, 0));
double desiredOffset = ss.HorizontalOffset - (center - itemPosition.X) + (centerItem.ActualWidth / 2);
ss.ScrollToHorizontalOffset(desiredOffset);
centerItem.Focus();
}
This block of code effectively determines which visible list element is overlapping the center line of the list and snaps that element to the exact center position. The snapping is a little abrupt, so I'll have to look into some kind of animation, but otherwise I'm fairly happy with it! I'll probably use something from here for animations: http://blogs.msdn.com/b/delay/archive/2009/08/04/scrolling-so-smooth-like-the-butter-on-a-muffin-how-to-animate-the-horizontal-verticaloffset-properties-of-a-scrollviewer.aspx
Edit: Well that didn't take long. I expanded the ScrollViewerOffsetMediator to include HorizontalOffset and then simply created the animation as suggested in the above post. Works like a charm. Hope this helps someone eventually.
Edit2: Here's the full code for SnapList:
SnapList.xaml
SnapList.xaml.cs
Note that I got pretty lazy as this project went on an hard-coded some of it. Some discretion will be needed to determine what you do and don't want from this code. Still, I think this should work pretty well as a starting point for anyone who wants this functionality.
The code has also changed from what I pasted above; I found that using Windows.GetWindow gave bad results when the list was housed in a control that could move. I made it so you can assign a control for your movement to be relative to (recommended that be the control just above your list in the hierarchy). I think a few other things changed as well; I've added a lot of customization options including being able to define a custom focal point for the list.

Related

Trigger repaint on custom control after being offscreen/obscured?

I've got a few custom controls that are covered in images, and if they get dragged off screen and back on, the image isn't repainted properly. I've got on paint overriden for these various controls, and they seem to work fine, other than they don't get drawn properly if dragged off screen on and on again. Anyone know why this might happen and/or a solution?
Edit: there seem to be issues with some of them even if the dialog is simply moved resized too fast, rather than just if it's taken off screen. They start looking like they've been drawn on top of themselves. Which kind of makes sense, but I can't figure out how to cure it.
Edit 2: These are custom buttons with fourstates (hover, click, normal, disabled), so I don't think the container thing is the issue I don't think..? The OnPaint code is:
private void CQPButton_Paint(object sender, PaintEventArgs e)
{
e.Graphics.Clear(BackColor);
if (BackgroundImage != null)
e.Graphics.DrawImage(BackgroundImage, e.ClipRectangle);
if (Image != null)
{
RectangleF rect = new RectangleF();
rect.X = (float)((e.ClipRectangle.Width - Image.Size.Width) / 2.0);
rect.Y = (float)((e.ClipRectangle.Height - Image.Size.Height) / 2.0);
rect.Width = Image.Width;
rect.Height = Image.Height;
e.Graphics.DrawImage(Image, rect);
}
if (Text != null)
{
SizeF size = e.Graphics.MeasureString(this.Text, this.Font);
// Center the text inside the client area of the PictureButton.
e.Graphics.DrawString(this.Text,
this.Font,
new SolidBrush(this.ForeColor),
(this.ClientSize.Width - size.Width) / 2,
(this.ClientSize.Height - size.Height) / 2);
}
}
I've tried forcing repaint on various events, LocationChanged and Move to try and deal with the resize issue, ClientSizeChanged to try and deal with when they're off screen, and nothing is sticking. I don't know what I'm missing...
I completely changed my answer after seeing the code snippet. It has a bug:
RectangleF rect = new RectangleF();
rect.X = (float)((e.ClipRectangle.Width - Image.Size.Width) / 2.0);
rect.Y = (float)((e.ClipRectangle.Height - Image.Size.Height) / 2.0);
Using e.ClipRectangle is incorrect here, it is a value that always changes, depending on what part of the control needs to be repainted. And yes, it changes most when you resize the control or drag it partially off the screen. You need to use the actual size of your control:
rect.X = (float)((this.ClientSize.Width - Image.Size.Width) / 2.0);
rect.Y = (float)((this.ClientSize.Height - Image.Size.Height) / 2.0);

Custom panel layout doesn't work as expected when animating (WPF)

I've got a custom (and getting complex) TabControl. It's a gathering of many sources, plus my own wanted features. In it is a custom Panel to show the headers of the TabControl. Its features are to compress the size of the TabItems until they reached their minimum, and then activates scrolling features (in the Panel, again). There is also another custom panel to hold a single button, that renders on the right of the TabItems (it's a "new tab" button).
It all works great, until I try to animate the scrolling.
Here are some relevant snippets :
In the CustomTabPanel (C#, overriding Panel and implementing IScrollInfo):
private readonly TranslateTransform _translateTransform = new TranslateTransform();
public void LineLeft()
{
FirstVisibleIndex++;
var offset = HorizontalOffset + _childRects[0].Width;
if (offset < 0 || _viewPort.Width >= _extent.Width)
offset = 0;
else
{
if (offset + _viewPort.Width > _extent.Width)
offset = _extent.Width - _viewPort.Width;
}
_offset.X = offset;
if (_scrollOwner != null)
_scrollOwner.InvalidateScrollInfo();
//Animate the new offset
var aScrollAnimation = new DoubleAnimation(_translateTransform.X, -offset,
new Duration(this.AnimationTimeSpan), FillBehavior.HoldEnd) { AccelerationRatio = 0.5, DecelerationRatio = 0.5 };
aScrollAnimation.Completed += ScrollAnimationCompleted;
_translateTransform.BeginAnimation(TranslateTransform.XProperty, aScrollAnimation , HandoffBehavior.SnapshotAndReplace);
//End of animation
// These lines are the only ones needed if we remove the animation
//_translateTransform.X = -offset;
//InvalidateMeasure();
}
void ScrollAnimationCompleted(object sender, EventArgs e)
{
InvalidateMeasure();
}
the _translateTransform is initialized in the constructor :
base.RenderTransform = _translateTransform;
Again, everything is fine if I remove the animation part and just replace it with the commented out lines at the end.
I must also point out that the problem is NOT with the animation itself. That part works out well. The problem is about when I remove some tab items : all the layout then screws up. The TranslateTransformation seems to hold on some wrong value, or something.
Thanks in advance.
Well. As it's often the case, I kept working on the thing, and... answered myself.
Could still be useful for other people, so here was the catch. In the line :
var aScrollAnimation = new DoubleAnimation(_translateTransform.X, -offset, new Duration(this.AnimationTimeSpan), FillBehavior.HoldEnd)
{ AccelerationRatio = 0.5, DecelerationRatio = 0.5 };
the FillBehavior should have been FillBehavior.Stop.
As easy as that!

Creating chess GUI in WPF

Firstly: apologies if this is a duplicate post. Things got a bit confusing as I'm trying to post/register at same time.
I started investigating running UCI chess engines from a simple WPF window, got the hang of having the chess engine running onf a different thread to the interface, and have created a reasonably servcieable text-based front end.
I'm getting a bit more ambitious now, and would like to start building a GUI with chess pieces on it that will feed the player's moves to the chess engine, and represent the engine's moves on the board as well. I'm aiming for draggable pieces rather than clicking squares.
My current attempts involve using draggable user controls for the pieces on a <canvas> element. I'd be really interested to hear how other, more experienced WPF/.NET programmers would approach this, as I'm not entirely convinced I'm on the right track.
For example: would it be better to use a uniform grid and drag piece data between child elements? Should I create an abstract 'piece' class from which pieces such as pawns could derive? That kind of thing.
Any thoughts? This isn't a homework assignment or anything, just something I'm noodling around with in my spare time as an exercise.
I have implemented a chess board for my Silverlight Online Chess system.
Here is how I did it.
I made a seperate user control for the chess board
I added a grid 8x8 onto the control
I then added 64 Borders shading each one a different color (dark squares and light squares) Make sure to name each one. Each of the borders were placed on the grid using the Grid.Row and Grid.Col properties.
Within each Border I added an Image that will hold the chess piece image.
You will have to code some methods around setting the image to the correct chess piece based on your current game state.
Each of the Images received the same event (this is important), all 64 call the same piece of code:
MouseLeftButtonDown="Image_MouseLeftButtonDown"
MouseMove="Image_MouseMove"
MouseLeftButtonUp="Image_MouseLeftButtonUp"
The idea behind these 3 events is that we record when I click on the image (MouseLeftButtonDown) that gets me the origin of the click, then I call the event as the mouse is moving, that allows me to update the screen as the piece is moving, and the last event I record when I let go of the mouse button (MouseLeftButtonUp), this allows me to get the destination and send the move to my chess engine. Once the move is recorded by the chess engine I just redraw the chess board.
private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Image image = (Image)sender;
Border border = (Border)image.Parent;
image.CaptureMouse();
isMouseCapture = true;
mouseXOffset = e.GetPosition(border).X;
mouseYOffset = e.GetPosition(border).Y;
var chessPiece = (Image) sender;
var chessSquare = (Border) chessPiece.Parent;
var row = (byte) (Grid.GetRow(chessSquare));
var column = (byte) (Grid.GetColumn(chessSquare) - 1);
if (engine.HumanPlayer == ChessPieceColor.White)
{
SelectionChanged(row, column, false);
}
else
{
SelectionChanged((byte)(7 - row), (byte)(7 - column), false);
}
}
SelectionChanged is my own method for recording what source square the user selected.
isMouseCapture is also my own variable for recording when the user started draging the piece.
private void Image_MouseMove(object sender, MouseEventArgs e)
{
Image image = (Image)sender;
Border border = (Border)image.Parent;
if (!currentSource.Selected)
{
image.ReleaseMouseCapture();
isMouseCapture = false;
translateTransform = new TranslateTransform();
translateTransform.X = 0;
translateTransform.Y = 0;
mouseXOffset = 0;
mouseYOffset = 0;
}
if (isMouseCapture)
{
translateTransform = new TranslateTransform();
translateTransform.X = e.GetPosition(border).X - mouseXOffset;
translateTransform.Y = e.GetPosition(border).Y - mouseYOffset;
image.RenderTransform = translateTransform;
CalculateSquareSelected((int)translateTransform.X, (int)translateTransform.Y, false);
}
}
In the above CalculareSquareSelected converts the pixels moved to where I think the piece is moving to in the 8x8 chess board. For example say I moved 100 pixels and the chess board square is only 50 pixels than I moved 2 chess board squares.
private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (translateTransform == null)
{
return;
}
Image image = (Image)sender;
image.ReleaseMouseCapture();
isMouseCapture = false;
if (translateTransform.X > 10 || translateTransform.Y > 10 || translateTransform.X < -10 || translateTransform.Y < -10)
{
CalculateSquareSelected((int)translateTransform.X, (int)translateTransform.Y, true);
}
translateTransform = new TranslateTransform();
translateTransform.X = 0;
translateTransform.Y = 0;
mouseXOffset = 0;
mouseYOffset = 0;
image.RenderTransform = translateTransform;
}
If you have any questions feel free to contact me.

How to change the direction of wpf marquee dynamically?

I want to change the direction of my marquee on changeDirection button click.
My code for changing direction is :
private void changeDirection_click(object sender, RoutedEventArgs e)
{
if (_marqueeType == MarqueeType.RightToLeft)
{
_marqueeType = MarqueeType.LeftToRight;
StartMarqueeing(_marqueeType);
}
else if (_marqueeType == MarqueeType.LeftToRight)
{
_marqueeType = MarqueeType.RightToLeft;
StartMarqueeing(_marqueeType);
}
}
And code for start marquee is :
public void StartMarqueeing(MarqueeType marqueeType)
{
double height = canMain.ActualHeight - marqueeList.ActualHeight;
marqueeList.Margin = new Thickness(0, 0, 0, 0);
doubleAnimation.From = -marqueeList.ActualWidth;
doubleAnimation.To = canMain.ActualWidth;
doubleAnimation.RepeatBehavior = RepeatBehavior.Forever;
doubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(_marqueeTimeInSeconds));
if (marqueeType == MarqueeType.RightToLeft)
{
Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(Canvas.Right)"));
_storyBoard.Children.Add(doubleAnimation);
_storyBoard.Begin(marqueeList, true);
}
else if (marqueeType == MarqueeType.LeftToRight)
{
Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(Canvas.Left)"));
_storyBoard.Children.Add(doubleAnimation);
_storyBoard.Begin(marqueeList, true);
}
}
Now here I am able to change the direction from Right to Left only first time.
But when I am change it from Left to Right it’s not changing the marquee position Left to Right.
It looks like you left out a _storyboard = new Storyboard(), perhaps at the top of the StartMarqueeing method.
From what I see it appears that every call to StartMarqueeing will add an additional DoubleAnimation to the storyboard, then start it again. So all the old DoubleAnimations will be recreated, and it looks like they take precedence.
Try creating a new Storyboard object each time, not just re-using it and adding to its children collection.
Update
Oh, now I see the problem. You should not be setting both (Canvas.Left) and (Canvas.Right). Use only one of the two: That's all you need anyway, and using both will give the Canvas conflicting instructions. Traditionally people use (Canvas.Left). I think that's what Canvas selects, which is what is causing your asymmetry.
You may wonder why I say you are using both when you don't think your two animations every run at the same time. Actually they do: The first animation runs then holds the value on the animated property until it is removed or bumped off by another animation. If the second animation then runs and modifies a different property it doesn't bump off the first animation so the first animation's value is still present.
The bottom line is, using (Canvas.Left) on both animations should fix it as long as you are using the default HandoffBehavior.SnapshotAndReplace.

Selecting an object on a WPF Canvas?

I have a WPF Canvas with some Ellipse objects on it (displayed as circles). Each circle is from a collection class instance which is actually a custom hole pattern class. Each pattern has a certain number of circles, and each circle then gets added to the canvas using an iteration over the collection using the code below.
So, the canvas is populated with a bunch of circles and each circle belongs to a certain pattern instance. You can see a screenshot here: http://twitpic.com/1f2ci/full
Now I want to add the ability to click on a circle on the canvas, and be able to determine the collection it belongs to, so that I can then do some more work on the selected pattern to which that circle belongs.
public void DrawHoles()
{
// Iterate over each HolePattern in the HolePatterns collection...
foreach (HolePattern HolePattern in HolePatterns)
{
// Now iterate over each Hole in the HoleList of the current HolePattern...
// This code adds the HoleEntity, HoleDecorator, and HoleLabel to the canvas
foreach (Hole Hole in HolePattern.HoleList)
{
Hole.CanvasX = SketchX0 + (Hole.AbsX * _ZoomScale);
Hole.CanvasY = SketchY0 - (Hole.AbsY * _ZoomScale);
canvas1.Children.Add(Hole.HoleEntity);
}
}
}
All FrameworkElements have a Tag property which is of type object that can be used to hold arbitrary information. You could assign the HolePattern to the Tag property and easily use that later to get the associated collection.
i.e.:
...
Hole.HoleEntity.Tag = HolePattern as object;
canvas1.Children.Add(Hole.HoleEntity);
later on in the click event:
event(object sender,....)
{
Ellipse e = sender as Ellipse;
HolePattern hp = e.Tag as HolePattern;
...
}
So you probably already read my reply where I said I had it working. And it does work perfectly, (except that it requires great precision with the mouse), but I want to ask this: is it really smart to add an event handler to EVERY ellipse that gets added to a canvas? Now I don't know what kind of memory bog that could be, or maybe it is a piece of cake for WPF and Windows to handle.
In a practical case, I guess there would be not more that 30-50 holes even on a screen that had multiple patterns, but still; FIFTY event handlers? It just seems scary. And actually, each "Hole" is visually represented by two concentric circles and a text label (see the screenshow here: http://twitpic.com/1f2ci/full ), and I know the user would expect to be able to click on any one of those elements to select a hole. That means an event handler on 3 elements for every hole. Now we could be talking about 100 or more event handlers.
It seems like there should be a solution where you could have just one event handler on the Canvas and read the element reference under the mouse, then work off of that to get the .Tag property of that elment, and so on.
I thought I'd post my final and more refined solution in case it helps anyone else.
void canvas1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
int ClickMargin = 2;// Adjust here as desired. Span is in both directions of selected point.
var ClickMarginPointList = new Collection<Point>();
Point ClickedPoint = e.GetPosition(canvas1);
Point ClickMarginPoint=new Point();
for (int x = -1 * ClickMargin; x <= ClickMargin; x++)
{
for (int y = -1 * ClickMargin; y <= ClickMargin; y++)
{
ClickMarginPoint.X = ClickedPoint.X + x;
ClickMarginPoint.Y = ClickedPoint.Y + y;
ClickMarginPointList.Add(ClickMarginPoint);
}
}
foreach (Point p in ClickMarginPointList)
{
HitTestResult SelectedCanvasItem = System.Windows.Media.VisualTreeHelper.HitTest(canvas1, p);
if (SelectedCanvasItem.VisualHit.GetType().BaseType == typeof(Shape))
{
var SelectedShapeTag = SelectedCanvasItem.VisualHit.GetValue(Shape.TagProperty);
if (SelectedShapeTag!=null && SelectedShapeTag.GetType().BaseType == typeof(Hole))
{
Hole SelectedHole = (Hole)SelectedShapeTag;
SetActivePattern(SelectedHole.ParentPattern);
SelectedHole.ParentPattern.CurrentHole = SelectedHole;
return; //Get out, we're done.
}
}
}
}

Resources