Search Results

Search found 16 results on 1 pages for 'measureoverride'.

Page 1/1 | 1 

  • WPF layout calls MeasureOverride repeatedly in increments of 2?

    - by Scott Whitlock
    I've run into a case where I have a custom Panel (inherits from Panel) and I'm using it as an ItemsPanel in a ListView. When I resize the container that it's in, if I resize it smaller, my panel's MeasureOverride function gets called once, but if I resize it larger (let's say from 100 to 300), it calls MeasureOverride and ArrangeOverride for every value between 100 and 300, in increments of 2 (so 102, 104, etc.). The weird thing is that the container resizes right away (its size gets to 300 immediately). It doesn't seem to matter what I return from MeasureOverride - it just does this. I wish I could make it happen in a really small application and post it here, but I haven't been able to reproduce it like that yet. I can reproduce it all day in my app though. Does anyone know what could cause this?

    Read the article

  • Need help understanding WPF MeasureOverride and ArrangeOverride infinity and 0 sizes

    - by Scott Bilas
    I'm trying to build a simple panel that contains one child and will snap it to nearest grid sizes. I'm having a hard time figuring out how to do this by overriding MeasureOverride and ArrangeOverride. Here's what I'm after: I want my panel to tell its owner that (a) it wants to be as large as possible, then (b) when it finds out what that size is, it will size itself and its child UIElement according to the nearest smaller snap point. So if we're snapping to 10's, and I can be in a region no bigger than 192x184, the panel will tell its parent container "my actual size is going to be 190x180". That way anything bordering my control will be able to align to its edges, as opposed to the potential space. When I put my panel inside of a Grid, I get either 0 or PositiveInfinity (I forget) for the incoming size in the overrides, but what I need to know is "how big can my space actually get?" not infinities.. Part of the problem I think is what WPF considers magic values of PositiveInfinity and 0 for size. I need a way to say, via MeasureOverride "I can be as big as you will allow me" and in ArrangeOverride to actually size to the snapped size. Or am I going about this the completely wrong way? Measuring and arranging looks very complicated, just from wandering around a little in the code for the standard panels in Reflector.

    Read the article

  • How can I force a ListView with a custom panel to re-measure when the ListView width goes below the

    - by Scott Whitlock
    Sorry for the long winded question (I'm including background here). If you just want the question, go to the end. I have a ListView with a custom Panel implementation that I'm using to implement something similar to a WrapPanel, but not quite. I'm overriding the MeasureOverride and ArrangeOverride methods in the custom panel. If I do the naive implementation of a WrapPanel in the MeasureOverride method it doesn't work when the ListView is resized. Let's say the custom panel does a measure and the constraint is a width of 100 and let's say I have 3 items that are 40 wide each. The naive approach is to return a size of 80,80 but when I resize the window that the ListView is in, down to say 75, it just turns on the horizontal scrollbar and never calls measure or arrange again (it does keep measuring and arranging if the width is greater than 80). To get around this, I hard coded the measurement to only have a width of the widest item. Then in the arrange, it gives me more space than I asked for and I use as much horizontal space as I can before wrapping. If I resize the window smaller than the smallest item in the ListView, then it turns on the scrollbar, which is great. Unfortunately this is causing a big problem when I have one of these ListViews with a custom panel nested inside of another one. The outside one works ok, but I can't get the inside one to "take as much as it needs". It always sizes to the smallest item, and the only way around it is to set the MinWidth to be something greater than zero. Anyway, stepping back for a second, I think the real way to fix this is to go back to the Naive implementation of the WrapPanel but force it to re-measure when the ListView width goes below the Size I previously returned as a measurement. That should solve my problem with the nested one. So, that's my question: I have a ListView with a custom panel If I return a measurement width on the panel and the ListView is resized to less than that width, it stops calling MeasureOverride How can I get it to continue calling MeasureOverride?

    Read the article

  • Trouble with custom WPF Panel-derived class

    - by chaiguy
    I'm trying to write a custom Panel class for WPF, by overriding MeasureOverride and ArrangeOverride but, while it's mostly working I'm experiencing one strange problem I can't explain. In particular, after I call Arrange on my child items in ArrangeOverride after figuring out what their sizes should be, they aren't sizing to the size I give to them, and appear to be sizing to the size passed to their Measure method inside MeasureOverride. Am I missing something in how this system is supposed to work? My understanding is that calling Measure simply causes the child to evaluate its DesiredSize based on the supplied availableSize, and shouldn't affect its actual final size. Here is my full code (the Panel, btw, is intended to arrange children in the most space-efficient manner, giving less space to rows that don't need it and splitting remaining space up evenly among the rest--it currently only supports vertical orientation but I plan on adding horizontal once I get it working properly): protected override Size MeasureOverride( Size availableSize ) { foreach ( UIElement child in Children ) child.Measure( availableSize ); return availableSize; } protected override System.Windows.Size ArrangeOverride( System.Windows.Size finalSize ) { double extraSpace = 0.0; var sortedChildren = Children.Cast<UIElement>().OrderBy<UIElement, double>( new Func<UIElement, double>( delegate( UIElement child ) { return child.DesiredSize.Height; } ) ); double remainingSpace = finalSize.Height; double normalSpace = 0.0; int remainingChildren = Children.Count; foreach ( UIElement child in sortedChildren ) { normalSpace = remainingSpace / remainingChildren; if ( child.DesiredSize.Height < normalSpace ) // if == there would be no point continuing as there would be no remaining space remainingSpace -= child.DesiredSize.Height; else { remainingSpace = 0; break; } remainingChildren--; } extraSpace = remainingSpace / Children.Count; double offset = 0.0; foreach ( UIElement child in Children ) { //child.Measure( new Size( finalSize.Width, normalSpace ) ); double value = Math.Min( child.DesiredSize.Height, normalSpace ) + extraSpace; child.Arrange( new Rect( 0, offset, finalSize.Width, value ) ); offset += value; } return finalSize; }

    Read the article

  • WPF Layout algorithm woes - control will resize, but not below some arbitrary value.

    - by Quantumplation
    I'm working on an application for a client, and one of the requirements is the ability to make appointments, and display the current week's appointments in a visual format, much like in Google Calender's or Microsoft Office. I found a great (3 part) article on codeproject, in which he builds a "RangePanel", and composes one for each "period" (for example, the work day.) You can find part 1 here: http://www.codeproject.com/KB/WPF/OutlookWpfCalendarPart1.aspx The code presents, but seems to choose an arbitrary height value overall (440.04), and won't resize below that without clipping. What I mean to say, is that the window/container will resize, but it just cuts off the bottom of the control, instead of recalculating the height of the range panels, and the controls in the range panels representing the appointment. It will resize and recalculate for greater values, but not less. Code-wise, what's happening is that when you resize below that value, first the "MeasureOverride" is called with the correct "new height". However, by the time the "ArrangeOverride" method is called, it's passing the same 440.04 value as the height to arrange to. I need to find a solution/workaround, but any information that you can provide that might direct me for things to look into would also be greatly appreciated ( I understand how frustrating it is to debug code when you don't have the codebase in front of you. :) ) The code for the various Arrange and Measure functions are provided below. The "CalendarView" control has a "CalendarViewContentPresenter", which handles several periods. Then, the periods have a "CalendarPeriodContentPresenter", which handles each "block" of appointments. Finally, the "RangePanel" has it's own implementation. (To be honest, i'm still a bit hazy on how the control works, so if my explanations are a bit hazy, the article I linked probably has a more cogent explanation. :) ) CalendarViewContentPresenter: protected override Size ArrangeOverride(Size finalSize) { int columnCount = this.CalendarView.Periods.Count; Size columnSize = new Size(finalSize.Width / columnCount, finalSize.Height); double elementX = 0; foreach (UIElement element in this.visualChildren) { element.Arrange(new Rect(new Point(elementX, 0), columnSize)); elementX = elementX + columnSize.Width; } return finalSize; } protected override Size MeasureOverride(Size constraint) { this.GenerateVisualChildren(); this.GenerateListViewItemVisuals(); // If it's coming back infinity, just return some value. if (constraint.Width == Double.PositiveInfinity) constraint.Width = 10; if (constraint.Height == Double.PositiveInfinity) constraint.Height = 10; return constraint; } CalendarViewPeriodPersenter: protected override Size ArrangeOverride(Size finalSize) { foreach (UIElement element in this.visualChildren) { element.Arrange(new Rect(new Point(0, 0), finalSize)); } return finalSize; } protected override Size MeasureOverride(Size constraint) { this.GenerateVisualChildren(); return constraint; } RangePanel: protected override Size ArrangeOverride(Size finalSize) { double containerRange = (this.Maximum - this.Minimum); foreach (UIElement element in this.Children) { double begin = (double)element.GetValue(RangePanel.BeginProperty); double end = (double)element.GetValue(RangePanel.EndProperty); double elementRange = end - begin; Size size = new Size(); size.Width = (Orientation == Orientation.Vertical) ? finalSize.Width : elementRange / containerRange * finalSize.Width; size.Height = (Orientation == Orientation.Vertical) ? elementRange / containerRange * finalSize.Height : finalSize.Height; Point location = new Point(); location.X = (Orientation == Orientation.Vertical) ? 0 : (begin - this.Minimum) / containerRange * finalSize.Width; location.Y = (Orientation == Orientation.Vertical) ? (begin - this.Minimum) / containerRange * finalSize.Height : 0; element.Arrange(new Rect(location, size)); } return finalSize; } protected override Size MeasureOverride(Size availableSize) { foreach (UIElement element in this.Children) { element.Measure(availableSize); } // Constrain infinities if (availableSize.Width == double.PositiveInfinity) availableSize.Width = 10; if (availableSize.Height == double.PositiveInfinity) availableSize.Height = 10; return availableSize; }

    Read the article

  • WPF: Order of stretch sizing

    - by RFBoilers
    I'm creating a modal dialog window which contains three essential parts: a TextBlock containing instructions, a ContentControl for the dialog panel, and a ContentControl for the dialog buttons. Each of these parts are contained in a separate Grid row. I have some specific constraints when it comes to how the dialog should be sized. The issue I'm having is with the instructions TextBlock. I want the instructions to be as wide as the ContentControl for the dialog panel. The instructions should then wrap and grow vertically as needed. Should the instructions not be able to grow vertically, then it should begin to grow horizontally. Getting the instructions to be the width of the ContentControl and grow vertically was simple. The part I can't seem to figure out is how to get it to grow horizontally when out of vertical space. My initial thought was to create a class that extends TextBlock and override MeasureOverride. However, that method is sealed. Currently, I'm playing with the idea of have the dialog Window override MeasureOverride to calculate the available size for the instructions block. Am I missing a much simpler way of accomplishing this? Does anyone have any better ideas than this? Messing with MeasureOverride seems like it will be a lot of work. Here is some sample code to give you a general idea of how the dialog is laid out: <Window x:Class="Dialogs.DialogWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="dialogWindow" ShowInTaskbar="False" WindowStyle="None" AllowsTransparency="True" Background="Transparent" ResizeMode="NoResize" SizeToContent="WidthAndHeight" WindowStartupLocation="CenterScreen"> <Border Style="{StaticResource WindowBorderStyle}" Margin="15"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <TextBlock Margin="25,5" VerticalAlignment="Top" HorizontalAlignment="Left" Text="{Binding Instructions}" TextWrapping="Wrap" Width="{Binding ElementName=panelContentControl, Path=ActualWidth, Mode=OneWay}"/> <ContentControl x:Name="panelContentControl" Grid.Row="1" Margin="25,5" Content="{Binding PanelContent}"/> <ContentControl x:Name="buttonsContentControl" Grid.Row="2" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="25,5" Content="{Binding ButtonsContent}"/> </Grid> </Border> </Window>

    Read the article

  • How to write a custom control, which can auto resize just like TextBox in a grid cell?

    - by Cooper.Wu
    I have tried to override MeasureOverride, but the available size will not change when i resize a grid. which contains my control. class MyFrameworkElement : FrameworkElement { override Size MeasureOverride(Size available) { this.Width = available.Width; this.Height = available.Width this.UpdateLayout(); // do something... } } This works only when application start. How to implement a auto resize control, just like a TextBox in a grid cell. The TextBox will auto resize to fill grid cell if grid resized.

    Read the article

  • Uniform grid Rows and Columns

    - by Carlo
    I'm trying to make a grid based on a UniformGrid to show the coordinates of each cell, and I want to show the values on the X and Y axes like so: _A_ _B_ _C_ _D_ 1 |___|___|___|___| 2 |___|___|___|___| 3 |___|___|___|___| 4 |___|___|___|___| Anyway, in order to do that I need to know the number of columns and rows in the Uniform grid, and I tried overriding the 3 most basic methods where the arrangement / drawing happens, but the columns and rows in there are 0, even though I have some controls in my grid. What method can I override so my Cartesian grid knows how many columns and rows it has? C#: public class CartesianGrid : UniformGrid { protected override Size MeasureOverride(Size constraint) { Size size = base.MeasureOverride(constraint); int computedColumns = this.Columns; // always 0 int computedRows = this.Rows; // always 0 return size; } protected override Size ArrangeOverride(Size arrangeSize) { Size size = base.ArrangeOverride(arrangeSize); int computedColumns = this.Columns; // always 0 int computedRows = this.Rows; // always 0 return size; } protected override void OnRender(DrawingContext dc) { int computedColumns = this.Columns; // always 0 int computedRows = this.Rows; // always 0 base.OnRender(dc); } } XAML: <local:CartesianGrid> <Label Content="Hello" /> <Label Content="Hello" /> <Label Content="Hello" /> <Label Content="Hello" /> <Label Content="Hello" /> <Label Content="Hello" /> </local:CartesianGrid> Any help is greatly appreciated. Thanks!

    Read the article

  • WPF Blurry Images - Bitmap Class

    - by Luke
    I am using the following sample at http://blogs.msdn.com/dwayneneed/archive/2007/10/05/blurry-bitmaps.aspx within VB.NET. The code is shown below. I am having a problem when my application loads the CPU is pegging 50-70%. I have determined that the problem is with the Bitmap class. The OnLayoutUpdated() method is calling the InvalidateVisual() continously. This is because some points are not returning as equal but rather, Point(0.0,-0.5) Can anyone see any bugs within this code or know a better implmentation for pixel snapping a Bitmap image so it is not blurry? p.s. The sample code was in C#, however I believe that it was converted correctly. Imports System Imports System.Collections.Generic Imports System.Windows Imports System.Windows.Media Imports System.Windows.Media.Imaging Class Bitmap Inherits FrameworkElement ' Use FrameworkElement instead of UIElement so Data Binding works as expected Private _sourceDownloaded As EventHandler Private _sourceFailed As EventHandler(Of ExceptionEventArgs) Private _pixelOffset As Windows.Point Public Sub New() _sourceDownloaded = New EventHandler(AddressOf OnSourceDownloaded) _sourceFailed = New EventHandler(Of ExceptionEventArgs)(AddressOf OnSourceFailed) AddHandler LayoutUpdated, AddressOf OnLayoutUpdated End Sub Public Shared ReadOnly SourceProperty As DependencyProperty = DependencyProperty.Register("Source", GetType(BitmapSource), GetType(Bitmap), New FrameworkPropertyMetadata(Nothing, FrameworkPropertyMetadataOptions.AffectsRender Or FrameworkPropertyMetadataOptions.AffectsMeasure, New PropertyChangedCallback(AddressOf Bitmap.OnSourceChanged))) Public Property Source() As BitmapSource Get Return DirectCast(GetValue(SourceProperty), BitmapSource) End Get Set(ByVal value As BitmapSource) SetValue(SourceProperty, value) End Set End Property Public Shared Function FindParentWindow(ByVal child As DependencyObject) As Window Dim parent As DependencyObject = VisualTreeHelper.GetParent(child) 'Check if this is the end of the tree If parent Is Nothing Then Return Nothing End If Dim parentWindow As Window = TryCast(parent, Window) If parentWindow IsNot Nothing Then Return parentWindow Else ' Use recursion until it reaches a Window Return FindParentWindow(parent) End If End Function Public Event BitmapFailed As EventHandler(Of ExceptionEventArgs) ' Return our measure size to be the size needed to display the bitmap pixels. ' ' Use MeasureOverride instead of MeasureCore so Data Binding works as expected. ' Protected Overloads Overrides Function MeasureCore(ByVal availableSize As Size) As Size Protected Overloads Overrides Function MeasureOverride(ByVal availableSize As Size) As Size Dim measureSize As New Size() Dim bitmapSource As BitmapSource = Source If bitmapSource IsNot Nothing Then Dim ps As PresentationSource = PresentationSource.FromVisual(Me) If Me.VisualParent IsNot Nothing Then Dim window As Window = window.GetWindow(Me.VisualParent) If window IsNot Nothing Then ps = PresentationSource.FromVisual(window.GetWindow(Me.VisualParent)) ElseIf FindParentWindow(Me) IsNot Nothing Then ps = PresentationSource.FromVisual(FindParentWindow(Me)) End If End If ' If ps IsNot Nothing Then Dim fromDevice As Matrix = ps.CompositionTarget.TransformFromDevice Dim pixelSize As New Vector(bitmapSource.PixelWidth, bitmapSource.PixelHeight) Dim measureSizeV As Vector = fromDevice.Transform(pixelSize) measureSize = New Size(measureSizeV.X, measureSizeV.Y) Else measureSize = New Size(bitmapSource.PixelWidth, bitmapSource.PixelHeight) End If End If Return measureSize End Function Protected Overloads Overrides Sub OnRender(ByVal dc As DrawingContext) Dim bitmapSource As BitmapSource = Me.Source If bitmapSource IsNot Nothing Then _pixelOffset = GetPixelOffset() ' Render the bitmap offset by the needed amount to align to pixels. dc.DrawImage(bitmapSource, New Rect(_pixelOffset, DesiredSize)) End If End Sub Private Shared Sub OnSourceChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs) Dim bitmap As Bitmap = DirectCast(d, Bitmap) Dim oldValue As BitmapSource = DirectCast(e.OldValue, BitmapSource) Dim newValue As BitmapSource = DirectCast(e.NewValue, BitmapSource) If ((oldValue IsNot Nothing) AndAlso (bitmap._sourceDownloaded IsNot Nothing)) AndAlso (Not oldValue.IsFrozen AndAlso (TypeOf oldValue Is BitmapSource)) Then RemoveHandler DirectCast(oldValue, BitmapSource).DownloadCompleted, bitmap._sourceDownloaded RemoveHandler DirectCast(oldValue, BitmapSource).DownloadFailed, bitmap._sourceFailed ' ((BitmapSource)newValue).DecodeFailed -= bitmap._sourceFailed; // 3.5 End If If ((newValue IsNot Nothing) AndAlso (TypeOf newValue Is BitmapSource)) AndAlso Not newValue.IsFrozen Then AddHandler DirectCast(newValue, BitmapSource).DownloadCompleted, bitmap._sourceDownloaded AddHandler DirectCast(newValue, BitmapSource).DownloadFailed, bitmap._sourceFailed ' ((BitmapSource)newValue).DecodeFailed += bitmap._sourceFailed; // 3.5 End If End Sub Private Sub OnSourceDownloaded(ByVal sender As Object, ByVal e As EventArgs) InvalidateMeasure() InvalidateVisual() End Sub Private Sub OnSourceFailed(ByVal sender As Object, ByVal e As ExceptionEventArgs) Source = Nothing ' setting a local value seems scetchy... RaiseEvent BitmapFailed(Me, e) End Sub Private Sub OnLayoutUpdated(ByVal sender As Object, ByVal e As EventArgs) ' This event just means that layout happened somewhere. However, this is ' what we need since layout anywhere could affect our pixel positioning. Dim pixelOffset As Windows.Point = GetPixelOffset() If Not AreClose(pixelOffset, _pixelOffset) Then InvalidateVisual() End If End Sub ' Gets the matrix that will convert a Windows.Point from "above" the ' coordinate space of a visual into the the coordinate space ' "below" the visual. Private Function GetVisualTransform(ByVal v As Visual) As Matrix If v IsNot Nothing Then Dim m As Matrix = Matrix.Identity Dim transform As Transform = VisualTreeHelper.GetTransform(v) If transform IsNot Nothing Then Dim cm As Matrix = transform.Value m = Matrix.Multiply(m, cm) End If Dim offset As Vector = VisualTreeHelper.GetOffset(v) m.Translate(offset.X, offset.Y) Return m End If Return Matrix.Identity End Function Private Function TryApplyVisualTransform(ByVal Point As Windows.Point, ByVal v As Visual, ByVal inverse As Boolean, ByVal throwOnError As Boolean, ByRef success As Boolean) As Windows.Point success = True If v IsNot Nothing Then Dim visualTransform As Matrix = GetVisualTransform(v) If inverse Then If Not throwOnError AndAlso Not visualTransform.HasInverse Then success = False Return New Windows.Point(0, 0) End If visualTransform.Invert() End If Point = visualTransform.Transform(Point) End If Return Point End Function Private Function ApplyVisualTransform(ByVal Point As Windows.Point, ByVal v As Visual, ByVal inverse As Boolean) As Windows.Point Dim success As Boolean = True Return TryApplyVisualTransform(Point, v, inverse, True, success) End Function Private Function GetPixelOffset() As Windows.Point Dim pixelOffset As New Windows.Point() Dim ps As PresentationSource = PresentationSource.FromVisual(Me) If ps IsNot Nothing Then Dim rootVisual As Visual = ps.RootVisual ' Transform (0,0) from this element up to pixels. pixelOffset = Me.TransformToAncestor(rootVisual).Transform(pixelOffset) pixelOffset = ApplyVisualTransform(pixelOffset, rootVisual, False) pixelOffset = ps.CompositionTarget.TransformToDevice.Transform(pixelOffset) ' Round the origin to the nearest whole pixel. pixelOffset.X = Math.Round(pixelOffset.X) pixelOffset.Y = Math.Round(pixelOffset.Y) ' Transform the whole-pixel back to this element. pixelOffset = ps.CompositionTarget.TransformFromDevice.Transform(pixelOffset) pixelOffset = ApplyVisualTransform(pixelOffset, rootVisual, True) pixelOffset = rootVisual.TransformToDescendant(Me).Transform(pixelOffset) End If Return pixelOffset End Function Private Function AreClose(ByVal Point1 As Windows.Point, ByVal Point2 As Windows.Point) As Boolean Return AreClose(Point1.X, Point2.X) AndAlso AreClose(Point1.Y, Point2.Y) End Function Private Function AreClose(ByVal value1 As Double, ByVal value2 As Double) As Boolean If value1 = value2 Then Return True End If Dim delta As Double = value1 - value2 Return ((delta < 0.00000153) AndAlso (delta > -0.00000153)) End Function End Class

    Read the article

  • Inheriting System.Windows.Controls.Panel

    - by modosansreves
    I use the Panel to provide custom layout of UIElements. For this, I override MeasureOverride and ArrangeOverride. In ArrangeOverride proper locations are given to Children. In my application, there is a bunch of rather heavy (by number of visuals) children inside the panel, but only 2 of them are located inside the visible region at a time. Working with my application I feel like all the visuals are drown. I need to introduce a kind of 'virtualization' and make the children render (or take CPU cycles) selectively. How do I?

    Read the article

  • Window sizing constraints by content

    - by EFraim
    I want the window to respect MinWidth/MinHeight and MaxWidth/MaxHeight specifications of the content control inside. Some suggested using SizeToContent, but this only helps to set the initial window size, not the constraints. Others suggested overriding MeasureOverride and setting window's Min/Max height and width there, but this seems to be somewhat unclean, considering that such a trivial problem should surely have a purely declarative solution. Just to mention another solution which seems reasonable but does not work (and had been previously mentioned in an answer which got deleted): binding MinWidth of the window to MinWidth of the control does not take into account window decorations.

    Read the article

  • WPF 4.0 Custom panel won't show dynamically added controls in VS 2010 Designer

    - by Matt Ruwe
    I have a custom panel control that I'm trying to dynamically add controls within. When I run the application the static and dynamically added controls show up perfectly, but the dynamic controls do not appear within the visual studio designer. Only the controls placed declaratively in the XAML appear. I'm currently adding the dynamic control in the CreateUIElementCollection override, but I've also tried this in the constructor without success. Public Class CustomPanel1 Inherits Panel Public Sub New() End Sub Protected Overrides Function MeasureOverride(ByVal availableSize As System.Windows.Size) As System.Windows.Size Dim returnValue As New Size(0, 0) For Each child As UIElement In Children child.Measure(availableSize) returnValue.Width = Math.Max(returnValue.Width, child.DesiredSize.Width) returnValue.Height = Math.Max(returnValue.Height, child.DesiredSize.Height) Next returnValue.Width = If(Double.IsPositiveInfinity(availableSize.Width), returnValue.Width, availableSize.Width) returnValue.Height = If(Double.IsPositiveInfinity(availableSize.Height), returnValue.Height, availableSize.Height) Return returnValue End Function Protected Overrides Function ArrangeOverride(ByVal finalSize As System.Windows.Size) As System.Windows.Size Dim currentHeight As Integer For Each child As UIElement In Children child.Arrange(New Rect(0, currentHeight, child.DesiredSize.Width, child.DesiredSize.Height)) currentHeight += child.DesiredSize.Height Next Return finalSize End Function Protected Overrides Function CreateUIElementCollection(ByVal logicalParent As System.Windows.FrameworkElement) As System.Windows.Controls.UIElementCollection Dim returnValue As UIElementCollection = MyBase.CreateUIElementCollection(logicalParent) returnValue.Add(New TextBlock With {.Text = "Hello, World!"}) Return returnValue End Function Protected Overrides Sub OnPropertyChanged(ByVal e As System.Windows.DependencyPropertyChangedEventArgs) MyBase.OnPropertyChanged(e) End Sub End Class And my usage of this custom panel <Window x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:CustomPanel" Title="MainWindow" Height="364" Width="434"> <local:CustomPanel1> <CheckBox /> <RadioButton /> </local:CustomPanel1> </Window>

    Read the article

  • Silverlight - How do I make each item in a list box be the same height?

    - by NotDan
    How can I make a silverlight listbox have all items be the same size and have them take up 100% of the listbox height. I.e. 1 item would be the height of the listbox, 2 items would each be 50% of the height of the list box, etc... Edit - Here is the code public class UniformPanel : Panel { protected override Size MeasureOverride(Size availableSize) { Size panelDesiredSize = new Size(); for (int i = 0; i < Children.Count; i++) { UIElement child = Children[i]; child.Measure(availableSize); var childDesiredSize = child.DesiredSize; panelDesiredSize.Height += childDesiredSize.Height; if (panelDesiredSize.Width < childDesiredSize.Width) { panelDesiredSize.Width = childDesiredSize.Width; } } return panelDesiredSize; } protected override Size ArrangeOverride(Size finalSize) { double height = finalSize.Height/Children.Count; for (int i = 0; i < Children.Count; i++) { UIElement child = Children[i]; Size size = new Size(finalSize.Width, height); child.Arrange(new Rect(new Point(0, i * height), size)); } return finalSize; // Returns the final Arranged size } }

    Read the article

  • WPF - Adding ContentControl to Custom Canvas

    - by Alp Hancioglu
    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?

    Read the article

  • Silverlight performance with many loaded controls

    - by gius
    I have a SL application with many DataGrids (from Silverlight Toolkit), each on its own view. If several DataGrids are opened, changing between views (TabItems, for example) takes a long time (few seconds) and it freezes the whole application (UI thread). The more DataGrids are loaded, the longer the change takes. These DataGrids that slow the UI chanage might be on other places in the app and not even visible at that moment. But once they are opened (and loaded with data), they slow showing other DataGrids. Note that DataGrids are NOT disposed and then recreated again, they still remain in memory, only their parent control is being hidden and visible again. I have profiled the application. It shows that agcore.dll's SetValue function is the bottleneck. Unfortunately, debug symbols are not available for this Silverlight native library responsible for drawing. The problem is not in the DataGrid control - I tried to replace it with XCeed's grid and the performance when changing views is even worse. Do you have any idea how to solve this problem? Why more opened controls slow down other controls? I have created a sample that shows this issue: http://cenud.cz/PerfTest.zip UPDATE: Using VS11 profiler on the sample provided suggests that the problem could be in MeasureOverride being called many times (for each DataGridCell, I guess). But still, why is it slower as more controls are loaded elsewhere? Is there a way to improve the performance?

    Read the article

  • Telerik Object reference not set to an instance of an object

    - by Duncan
    Hi, I have a main form which contains multiple worker threads. These threads raise events which update Telerik controls on the main form. The event handlers contain code which check if InvokeRequired and BeginInvoke where required. At random interval I am receiving the following exception, and have no idea on how where to find this? I was wondering if the following is understandable to anyone to point me in the right direction. Thanks in advance System.Reflection.TargetInvocationException was unhandled Message="Exception has been thrown by the target of an invocation." Source="mscorlib" StackTrace: at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) at System.Delegate.DynamicInvokeImpl(Object[] args) at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme) at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj) at System.Threading.ExecutionContext.runTryCode(Object userData) at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme) at System.Windows.Forms.Control.InvokeMarshaledCallbacks() at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ScrollableControl.WndProc(Message& m) at Telerik.WinControls.RadControl.WndProc(Message& m) at Telerik.WinControls.UI.RadStatusStrip.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(ApplicationContext context) at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun() at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel() at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine) at MyFX.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: System.NullReferenceException Message="Object reference not set to an instance of an object." Source="Telerik.WinControls" StackTrace: at Telerik.WinControls.Layouts.ContextLayoutManager.LayoutQueue.RemoveOrphans(RadElement parent) at Telerik.WinControls.Layouts.ContextLayoutManager.LayoutQueue.Add(RadElement e) at Telerik.WinControls.RadElement.InvalidateArrange(Boolean recursive) at Telerik.WinControls.RadElement.InvalidateArrange() at Telerik.WinControls.RadElement.Measure(SizeF availableSize) at Telerik.WinControls.Layouts.ImageAndTextLayoutPanel.MeasureOverride(SizeF availableSize) at Telerik.WinControls.RadElement.MeasureCore(SizeF availableSize) at Telerik.WinControls.RadElement.Measure(SizeF availableSize) at Telerik.WinControls.Layouts.ContextLayoutManager.UpdateLayout() at Telerik.WinControls.Layouts.ContextLayoutManager.UpdateLayoutCallback(ILayoutManager manager)

    Read the article

1