Why Is InvalidateMeasure While In Arrange Pass Not Working? - wpf

I have following XAML:
<Grid>
<StackPanel>
<local:MyControl Background="Blue" AnotherControl="{x:Reference anotherControl}"/>
<local:MyAnotherControl Background="Red" x:Name="anotherControl"/>
</StackPanel>
</Grid>
The problem is when in MeasureOverride of MyControl I return (100, 20) back. Thought when in ArrangeOverride of MyControl I return the final size I recieve. Therefore the MyControl has ActualWidth the same as Window.
So far so good but while I am inside ArrangeOverride of MyControl and before I return size I invalidate measure of MyAnotherControl.
The end result is the MyAnotherControl is being measured but while in arrange pass and therefore its not notifying StackPanel that MyAnotherControl's desired size has changed. Futhermore as result StackPanel is not displayed properly.
It seems to me I found strange behavior in wpf when invalidating a control while I am in arrange pass. MyAnotherControl is not notifing its parent which is Stackpanel about size changed but it should.
Any solution to this?
If you resize the window it will all be arranged and drawn correctly. Why?
There are two stripes. The blue one and red one. Red shall appear with another height but it doesnt. When you resize the window and force remeasuing it works. Why is this strange behavior happening?
public class MyControl : Button
{
public MyAnotherControl AnotherControl
{
get;
set;
}
protected override Size MeasureOverride(Size constraint)
{
base.MeasureOverride(constraint);
return new Size(100, 20);
}
protected override Size ArrangeOverride(Size arrangeBounds)
{
base.ArrangeOverride(arrangeBounds);
AnotherControl.MyHeight = 50;
AnotherControl.InvalidateMeasure();
return arrangeBounds;
}
}
public class MyAnotherControl : Button
{
public double MyHeight
{
get;
set;
}
protected override Size MeasureOverride(Size constraint)
{
base.MeasureOverride(constraint);
return new Size(100, this.MyHeight > 0 ? this.MyHeight : 10);
}
protected override Size ArrangeOverride(Size arrangeBounds)
{
base.ArrangeOverride(arrangeBounds);
return arrangeBounds;
}
}

This is how wpf works. The stackpanel is just enumerating its children and calling their arrange within its arrange. If you call arrange on an element whose measure is invalid, it will be remeasured with the last available size. The onchilddesiredsizechanged of the parent won't be called so the measure of the parent won't be invalidated. You should probably just get the visual parent of the sibling and invalidate its measure.

Related

WPF - Adding ContentControl to Custom Canvas

I have a custom DrawingCanvas which is inherited from Canvas. When I add a ContentControl to DrawingCanvas with the following code nothing shows up.
GraphicsRectangle rect = new GraphicsRectangle(0, 0, 200, 200, 5, Colors.Blue);
DrawingContainer host = new DrawingContainer(rect);
ContentControl control = new ContentControl();
control.Width = 200;
control.Height = 200;
DrawingCanvas.SetLeft(control, 100);
DrawingCanvas.SetTop(control, 100);
control.Style = Application.Current.Resources["DesignerItemStyle"] as Style;
control.Content = host;
drawingCanvas.Children.Add(control);
GraphicsRectangle is a DrawingVisual and the constructor above draws a Rect with (0,0) top left point and length of 200 to the drawingContext of GraphicsRectangle. DrawingContainer is a FrameworkElement and it has one child, which is rect above, given with constructor. DrawingContainer implements GetVisualChild and VisualChildrenCount override methods. At last, Content property of ContentControl is set to the DrawingContainer to be able to show the DrawingVisual's content.
When I add the created ContentControl to a regular Canvas, control is showed correctly. I guess the reason is that DrawingCanvas doesn't implement ArrangeOverride method. It only implements MeasureOverride method. Also DrawingContainer doesn't implement Measure and
Arrange override methods. Any ideas?
As I thought the problem was missing ArrangeOverride method in DrawingCanvas. With the following ArrangeOverride method added to DrawingCanvas, ContentControls are showed correctly.
protected override Size ArrangeOverride(Size arrangeSize)
{
foreach (Visual child1 in children)
{
if (child1 is DrawingVisual)
continue;
ContentControl child = child1 as ContentControl;
GraphicsBase content = ((DrawingContainer)(child.Content)).GraphicsObject;
child.Arrange(new Rect(DrawingCanvas.GetLeft(child), DrawingCanvas.GetTop(child), content.Width, content.Height));
}
return arrangeSize;
}
where GraphicsBase is the base of the GraphicsRectangle class. In order to find the size of the GraphicsBase, I added width and height properties to GraphicsBase which are set in the constructor of GraphicsRectangle.

Problem with custom scrolling in custom panel

I'm coding a custom panel representing the hand of cards. It's a panel that will stack the cards horizontally. If there isn't enough space, each card will overlap part of the card left of it. Minimum part should be always visible. I accomplished this and this is the code:
using System;
using System.Windows;
using System.Windows.Controls;
namespace Hand
{
public class Hand : Panel
{
//TODO Should be dependancy property
private const double MIN_PART = 0.5;
protected override Size MeasureOverride(Size availableSize)
{
Size desiredSize = new Size();
foreach (UIElement element in this.Children)
{
element.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
desiredSize.Width += element.DesiredSize.Width;
desiredSize.Height = Math.Max(desiredSize.Height, element.DesiredSize.Height);
}
return desiredSize;
}
protected override Size ArrangeOverride(Size finalSize)
{
//percentage of the visible part of the child.
double part = 1;
Double desiredWidth = 0;
//TODO Check how to get desired size because without looping
//this.DesiredSize is minimum of available size and size returned from MeasureOverride
foreach (UIElement element in this.Children)
{
desiredWidth += element.DesiredSize.Width;
}
if (desiredWidth > this.DesiredSize.Width)
{
//Every, but the last child should be overlapped
double lastChildWidth = this.Children[this.Children.Count - 1].DesiredSize.Width;
part = (this.DesiredSize.Width - lastChildWidth) / (desiredWidth - lastChildWidth);
part = Math.Max(part, MIN_PART);
}
double x = 0;
foreach (UIElement element in this.Children)
{
Rect rect = new Rect(x, 0, element.DesiredSize.Width, element.DesiredSize.Height);
element.Arrange(rect);
finalSize.Width = x + element.DesiredSize.Width;
x += element.DesiredSize.Width * part;
}
return finalSize;
}
}
}
I would like to add scrollbar when minimum part is reached, so that the user could still be able to view all the cards. I cannot accomplish this. I tried with the ScrollViewer like this:
<Window x:Class="TestScrollPanel.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:h="clr-namespace:Hand;assembly=Hand"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ScrollViewer HorizontalScrollBarVisibility="Auto">
<h:Hand>
<Button Width="100">One</Button>
<Button Width="150">Two</Button>
<Button Width="200">Three</Button>
</h:Hand>
</ScrollViewer>
</Grid>
</Window>
But this doesn't work because once horizontal scrollbar is visible, MeasureOveride and ArrangeOverride of Hand panel is never called and even if it would be called, Hand would get desired size to arrange all children without overlapping.
Could this be made with ScrollViewer at all and if not, another ideas would be appreciated.
Thank you all for ypur help.
Jurica
Firstly, change your panel's logic to just the opposite: let MeasureOverride pack the cards as tightly as possible, and then let ArrangeOverride spread them evenly over whatever width is given.
Secondly, use the MinWidth property. Bind it to ScrollViewer.ActualWidth.
This way, if the cards can be tightly packed into width less than that of the ScrollViewer, then your Hand will be stretched to all available space. And if they can't, then the Hand's width will be just whatever you calculate it to.

WPF UserControl is not drawn when overriding MeasureOverride and ArrangeOverride

I have a UserControl looking like this:
<UserControl
MaxHeight="32"
MaxWidth="32"
MinHeight="25"
MinWidth="25">
<DockPanel>
<!-- some stuff -->
</DockPanel>
</UserControl>
In addition to the min/max size constraint, I want the control always being painted with Width = Height. So i override MeasureOverride and ArrangeOverride:
protected override Size MeasureOverride(Size availableSize)
{
var resultSize = new Size(0, 0);
((UIElement)Content).Measure(availableSize);
var sideLength = Math.Min(((UIElement)Content).DesiredSize.Width, ((UIElement)Content).DesiredSize.Height);
resultSize.Width = sideLength;
resultSize.Height = sideLength;
return resultSize;
}
protected override Size ArrangeOverride(Size finalSize)
{
((UIElement)Content).Arrange(new Rect(0, 0, finalSize.Width, finalSize.Height));
return finalSize;
}
I understand that I must call Measure and Arrange on every child of the UserControl. Since the DocPanel is the only child of my UserControl and (in my understanding) is stored in the Content property of the UserControl, I simply call Measure and Arrange on this Content property. However the UserControl is not displayed. What am I doing wrong?
Depending on how you are hosting your UserControl, the value returned from the Measure phase may not be used. If you have it setup in a Grid with star rows/columns or a DockPanel, then the final size may be completely different.
You would need to apply similar logic to the arrange phase, so it will effectively ignore any extra space it's given.
The following code should work, and is a bit cleaner:
protected override Size MeasureOverride(Size availableSize) {
var desiredSize = base.MeasureOverride(availableSize);
var sideLength = Math.Min(desiredSize.Width, desiredSize.Height);
desiredSize.Width = sideLength;
desiredSize.Height = sideLength;
return desiredSize;
}
protected override Size ArrangeOverride(Size finalSize) {
var sideLength = Math.Min(this.DesiredSize.Width, this.DesiredSize.Height);
return base.ArrangeOverride(new Size(sideLength, sideLength));
}

Creating SelectionBorder: Bit in the face by decimal rounding?

I am currently implementing a class called SelectionBorder in WPF. It's derived from the Shape class.
It basically looks like this:
public class SelectionBorder : Shape
{
public Point StartPoint {get; set;}
public PointCollection Points {get; set;}
public double StrokeLength {get; set;}
protected override Geometry DefiningGeometry{
get{
//Magic!
}
}
}
The StartPoint and Points properties determine the corners of the border. The border is a typical stroked line border (one black stroke, one invisible stroke like that: - - - -)
The problem that I have now is that since the corner points are freely choosable it's pretty common that the count of strokes (meaning black and invisible strokes) is not even (in fact not even an integer) and therefore the first stroke looks longer than the others (visible in the picture). This maybe doesn't seem to be a big deal but I later want to animate the border so that the strokes circle round the content. When doing this animation the tiny flaw in the static view becomes clearly visible and in my opinion is highly disturbing.
alt text http://img14.imageshack.us/img14/2874/selectionborder.png
The problem is that I tried to determine a StrokeLength that gets as close to the original StrokeLength as possible and creates an even number of strokes. However the problem I've run into is that WPF (obviously) can't display the whole precision of a double decimal StrokeLength and therefore the resulting stroke number is uneven once again.
Is there any workaround for this problem? Do you probably have another solution for my problem?
Thanks in advance!
EDIT: I retested and reviewed the code after a little break for fitness today and after all it happens only on very big StrokeLengths. I plan to use StrokeLengths of 2 where the little animation jumping does matter much less than I originally thought.
You could make more than one corner "un-matched" in that regard. For example, instead of having one point be the "source" and "destination" of the animated dashes, you could pick 2 points. One would be the "source", dashes appearing to march away from it in 2 directions, and another point be the "destination", where dashes converge and disappear.
GIMP, for example, animates selection dashed lines in this way and seems to pick a point closest to the lower-left for the "source" and a point closest to the upper-right for the "destination".
You could come up with some other scheme, as well.
Just remember that while it may look disturbing to you, most users will not care.
I just found a way that makes it way easier to create such an animated SelectionBorder.
Instead of creating the animation by moving an self-created AnimationPoint through animation I just animated the StrokeDashOffset property natively provided by the Shape class and setting the StrokeDashArray to define the StrokeLength.
It would look like this in XAML:
<namespace:SelectionBorder StrokeDashArray="2" AnimationDuration="0:0:1" Stroke="Black" />
The class looks like this:
public class SelectionBorder : Shape
{
private DoubleAnimation m_Animation;
private bool m_AnimationStarted;
public SelectionBorder()
{
IsVisibleChanged += OnIsVisibleChanged;
}
protected void OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (Visibility == Visibility.Visible)
{
StartAnimation();
}
else
{
StopAnimation();
}
}
public void StartAnimation()
{
if (m_AnimationStarted)
return;
if (m_Animation == null)
{
m_Animation = CreateAnimation();
}
BeginAnimation(StrokeDashOffsetProperty, m_Animation);
m_AnimationStarted = true;
}
protected virtual DoubleAnimation CreateAnimation()
{
DoubleAnimation animation = new DoubleAnimation();
animation.From = 0;
if (StrokeDashArray.Count == 0)
animation.To = 4;
else
animation.To = StrokeDashArray.First() * 2;
animation.Duration = AnimationDuration;
animation.RepeatBehavior = RepeatBehavior.Forever;
return animation;
}
public void StopAnimation()
{
if (m_AnimationStarted)
{
BeginAnimation(StrokeDashOffsetProperty, null);
m_AnimationStarted = false;
}
}
#region Dependency Properties
public Duration AnimationDuration
{
get { return (Duration)GetValue(AnimationDurationProperty); }
set { SetValue(AnimationDurationProperty, value); }
}
public static readonly DependencyProperty AnimationDurationProperty =
DependencyProperty.Register("AnimationDuration", typeof(Duration), typeof(SelectionBorder), new UIPropertyMetadata(new Duration(TimeSpan.FromSeconds(0.5))));
#endregion Dependency Properties
protected override Geometry DefiningGeometry
{
get
{
double width = (double.IsNaN(Width)) ? ((Panel)Parent).ActualWidth : Width;
double height = (double.IsNaN(Height)) ? ((Panel)Parent).ActualHeight : Height;
RectangleGeometry geometry = new RectangleGeometry(new Rect(0, 0, width, height));
return geometry;
}
}
}

WPF RichTextBox with no width set

I have the following XAML code:
<Window x:Class="RichText_Wrapping.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1">
<Grid>
<RichTextBox Height="100" Margin="2" Name="richTextBox1">
<FlowDocument>
<Paragraph>
This is a RichTextBox - if you don't specify a width, the text appears in a single column
</Paragraph>
</FlowDocument>
</RichTextBox>
</Grid>
... If you create this window in XAML, you can see that when you don't specify a width for the window, it wraps the text in a single column, one letter at a time. Is there something I'm missing? If it's a known deficiency in the control, is there any workaround?
This is a confirmed bug with the WPF RichTextBox. To fix it, Bind the PageWidth of the FlowDocument to the RichTextBox width, i.e.
<RichTextBox Name="rtb">
<FlowDocument Name="rtbFlowDoc" PageWidth="{Binding ElementName=rtb, Path=ActualWidth}" />
</RichTextBox>
EDIT:
Give the FlowDocument a name so that you can access it in the code behind and never new the flow document in codebehind.
Try binding the FlowDocument's width (one way) to the width of the container RichTextBox.
Worked for me...
The approach in this article worked for me:
WPF RichTextBox doesn't provide the functionality to adjust its width
to the text. As far as I know, RichTextBox use a FlowDocumentView in
its visual tree to render the Flowdocument. It will take the available
space to render its content, so it won't adjust its size to the
content. Since this is an internal class, it seems we cannot override
the layout process to let a RichTextBox to adjust its size to the
text.
Therefore, I think your approach is in the right direction.
Unfortunelately, based on my research, there is no straightforward way
to measure the size of the rendered text in a RichTextBox.
There is a workaround we can try. We can loop through the flowdocument
in RichTextBox recursively to retrieve all Run and Paragraph objects.
Then we convert them into FormattedText to get the size.
This article demonstrates how to convert a FlowDocument to
FormattedText. I also write a simple sample using the
FlowDocumentExtensions class in that article.
public Window2()
{
InitializeComponent();
StackPanel layoutRoot = new StackPanel();
RichTextBox myRichTextBox = new RichTextBox() { Width=20};
this.Content = layoutRoot;
layoutRoot.Children.Add(myRichTextBox);
myRichTextBox.Focus();
myRichTextBox.TextChanged += new TextChangedEventHandler((o,e)=>myRichTextBox.Width=myRichTextBox.Document.GetFormattedText().WidthIncludingTrailingWhitespace+20);
}
public static class FlowDocumentExtensions
{
private static IEnumerable<TextElement> GetRunsAndParagraphs(FlowDocument doc)
{
for (TextPointer position = doc.ContentStart;
position != null && position.CompareTo(doc.ContentEnd) <= 0;
position = position.GetNextContextPosition(LogicalDirection.Forward))
{
if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.ElementEnd)
{
Run run = position.Parent as Run;
if (run != null)
{
yield return run;
}
else
{
Paragraph para = position.Parent as Paragraph;
if (para != null)
{
yield return para;
}
}
}
}
}
public static FormattedText GetFormattedText(this FlowDocument doc)
{
if (doc == null)
{
throw new ArgumentNullException("doc");
}
FormattedText output = new FormattedText(
GetText(doc),
CultureInfo.CurrentCulture,
doc.FlowDirection,
new Typeface(doc.FontFamily, doc.FontStyle, doc.FontWeight, doc.FontStretch),
doc.FontSize,
doc.Foreground);
int offset = 0;
foreach (TextElement el in GetRunsAndParagraphs(doc))
{
Run run = el as Run;
if (run != null)
{
int count = run.Text.Length;
output.SetFontFamily(run.FontFamily, offset, count);
output.SetFontStyle(run.FontStyle, offset, count);
output.SetFontWeight(run.FontWeight, offset, count);
output.SetFontSize(run.FontSize, offset, count);
output.SetForegroundBrush(run.Foreground, offset, count);
output.SetFontStretch(run.FontStretch, offset, count);
output.SetTextDecorations(run.TextDecorations, offset, count);
offset += count;
}
else
{
offset += Environment.NewLine.Length;
}
}
return output;
}
private static string GetText(FlowDocument doc)
{
StringBuilder sb = new StringBuilder();
foreach (TextElement el in GetRunsAndParagraphs(doc))
{
Run run = el as Run;
sb.Append(run == null ? Environment.NewLine : run.Text);
}
return sb.ToString();
}
}
I copy pasted your code and its not in a single column, Do you have a width somewhere that is small? Maybe defined on the code behind for instance.
I noticed that I only had this issue when my default ScrollViewer style explicitly set HorizontalScrollBarVisibility=Hidden. Removing this setter (default value is Hidden anyway) fixed the single column issue for me in my RichTextBox.
Just for the record as I think this thread is missing some explanations as per the why: RichTextBox MeasureOverride implementation is like that. I won't call that a bug, maybe just a poor design behavior justified by the fact that just like mentioned above the FlowDocument is not cheap to measure due to its complexity. Bottom line, avoid unlimited Width constraint by binding MinWidth or wrap it in a limiting container.
/// <summary>
/// Measurement override. Implement your size-to-content logic here.
/// </summary>
/// <param name="constraint">
/// Sizing constraint.
/// </param>
protected override Size MeasureOverride(Size constraint)
{
if (constraint.Width == Double.PositiveInfinity)
{
// If we're sized to infinity, we won't behave the same way TextBox does under
// the same conditions. So, we fake it.
constraint.Width = this.MinWidth;
}
return base.MeasureOverride(constraint);
}

Resources