none
AccordionItem Content Resize at Runtime

    Question

  • Hi!!

    I'm using an Accordion Panel as the main navigational tool on a Web App.

    Inside this Accordion Panel Items is all the Data and Information of the Web App.

    Everything works smoothly until I came accross the need to resize the Content Height of the Selected Accordion Item at runtime. To be more precise inside the Content I have multiple Panels of Various Heights and there are all Collapsed( NOT Visible) until the user selects at Runtime to display one of them (only one at a time).

    I tried the obvious, like calling UpdateLayout()  or Measure() and Arrange() methods of the Accordion Panel Item Content, but with no luck. All I get is the appearance of the ScrollBars when the new Height I define based on a selection is bigger than the originally rendered by the Content. Supprisingly if I Unselect the Accordion Item and then Select it again , the Content renders to the desired height.

    I'm fairly new at Silverlight, so there is a chance I'm not seeing an easy solution or I'm trying to do something that is not valid, so I would appreciate any tips or suggestions.

    Sunday, May 24, 2009 5:00 PM

Answers

  • Hi,

    Thanks for reporting this.
    This is a known issue with the March 2009 Accordion. I'm hopeful we'll be fixing this issue for the Silverlight Toolkit June 2009 release.

    I'm not sure if there's a workaround you can use in the meanwhile. But I'll Ruurd (senior control developer) to follow up with you.

    In the meanwile, I suggest you just ignore this issue and wait for the June 2009 release.  

    Monday, May 25, 2009 7:42 PM

All replies

  • Hi,

    Thanks for reporting this.
    This is a known issue with the March 2009 Accordion. I'm hopeful we'll be fixing this issue for the Silverlight Toolkit June 2009 release.

    I'm not sure if there's a workaround you can use in the meanwhile. But I'll Ruurd (senior control developer) to follow up with you.

    In the meanwile, I suggest you just ignore this issue and wait for the June 2009 release.  

    Monday, May 25, 2009 7:42 PM
  • Ok, thank you very much for the quick reply.

    I will mark my post as resolved.

    Tuesday, May 26, 2009 3:54 AM
  • Hi,

     This behavior was by design, but we have decided to change it. Therefore, in some future release of Accordion your scenario should work!

     Thank you.

    Tuesday, June 02, 2009 12:19 PM
  • Did this change make it into the July 2009 release?

    I'm having the same issue that the AccordionItem doesn't resize to its Content at runtime.

    Friday, July 10, 2009 3:39 PM
  • Hi,

     please make sure you set ContentAlignments to stretch and have an accordion that allows flexible sizing (so not one with a fixed size).

    It should work, if not, please send repro.

    Thanks,

    Friday, July 10, 2009 3:46 PM
  • Here's a sample to reproduce what I'm seeing. I've set the VerticalContentAlignment to Stretch, but I'm not able to get the AccordionItem to resize at runtime.

    <UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:layoutToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Layout.Toolkit"
    x:Class="SilverlightApplication1.MainPage"
    Width="640" Height="480" VerticalContentAlignment="Stretch">

    <Grid x:Name="LayoutRoot" Background="White">
    <layoutToolkit:Accordion x:Name="accordion" Width="100" BorderBrush="Black" Margin="5">
    <layoutToolkit:AccordionItem Header="Header" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">
    <StackPanel Background="#FFD8D8D8" VerticalAlignment="Top">
    <TextBlock Text="Content 1" />
    <TextBlock Text="Content 2" />
    <TextBlock Text="Content 3" />
    </StackPanel>
    </layoutToolkit:AccordionItem>
    <layoutToolkit:AccordionItem Header="Header" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">
    <StackPanel Background="#FFD8D8D8" VerticalAlignment="Top">
    <TextBlock Text="Content 1" />
    <TextBlock Text="Content 2" />
    <TextBlock Text="Content 3" />
    </StackPanel>
    </layoutToolkit:AccordionItem>
    </layoutToolkit:Accordion>
    <Button x:Name="add" VerticalAlignment="Top" Content="Remove Content" Margin="110,5,0,0" HorizontalAlignment="Left" Click="remove_Click"/>
    <Button x:Name="remove" VerticalAlignment="Top" Content="Add Content" Margin="110,33,0,0" HorizontalAlignment="Left" Click="add_Click"/>
    </Grid>
    </UserControl>
     

     

    using System.Windows;
    using System.Windows.Controls;

    namespace SilverlightApplication1
    {
    public partial class MainPage
    {
    public MainPage()
    {
    InitializeComponent();
    }

    private void add_Click(object sender, RoutedEventArgs e)
    {
    foreach (AccordionItem item in accordion.Items)
    {
    StackPanel content = (StackPanel) item.Content;
    content.Children.Add(new TextBlock{Text = "Added Content"});
    }
    }

    private void remove_Click(object sender, RoutedEventArgs e)
    {
    foreach (AccordionItem item in accordion.Items)
    {
    StackPanel content = (StackPanel) item.Content;
    content.Children.RemoveAt(content.Children.Count - 1);
    }
    }
    }
    }

      

    Thanks for your attention,

    John

    Friday, July 10, 2009 5:17 PM
  • I have exactly the same problem - has there been any solution or workaround to this issue?

    Right now I am going to have to abandon using the Accordion just for this reason. Which is annoying seeing as it is a great screen real-estate saver!

    Nic

    Thursday, August 06, 2009 3:09 PM
  • OK - I have a work around for you. It's not ideal but works.

    I have amended your code slightly and added comments - I hope it is fairly obvious what it is doing. I also added some extra Accordion items to proove it works!

     

    public partial class MainPage : UserControl
        {
            AccordionItem _itmSel = null;
            AccordionItem _itmNonSel = null;
    
            public MainPage()
            {
                InitializeComponent();
            }
    
            //To make this work we need to know which item is selected and one that isn't
            //We can't unselect the selected one as it will be locked (I think this may only be 
    //
    in a non many selection mode?) So we test for the selected one and then grab a handle to a
    //non selected one (of course you could put something in not to keep grabbing a non
    //selected item once you have one) // //After we have done our work in the foreach loop - we select the non selected item to
    //de-select the first one. Call update layout and then add an event handler
    //(it doesn't work the other way around)
    private void add_Click(object sender, RoutedEventArgs e) { foreach (AccordionItem item in accordion.Items) { StackPanel content = (StackPanel) item.Content; content.Children.Add(new TextBlock{Text = "Added Content"}); if (item.IsSelected) { _itmSel = item; } else { _itmNonSel = item; } } if ((_itmSel!=null) && (_itmNonSel!=null)) { _itmNonSel.IsSelected = true; _itmNonSel.UpdateLayout();
    //Event handler assignment must be after the call to Update else doesn't work - go figure! _itmNonSel.LayoutUpdated += new EventHandler(_itmNonSel_LayoutUpdated); } } //In our event handler we remove the update handler and then reselect the original item //This will cause it to display the new item - albeit with a slight bounce (especially on the last one) // //Of course if this accordion is in a multiselect mode you will need to add
    //something to re-de-select the non selected item!
    void _itmNonSel_LayoutUpdated(object sender, EventArgs e) { _itmNonSel.LayoutUpdated -= _itmNonSel_LayoutUpdated; _itmSel.IsSelected = true; _itmSel.UpdateLayout(); _itmNonSel = null; _itmSel = null; } private void remove_Click(object sender, RoutedEventArgs e) { foreach (AccordionItem item in accordion.Items) { StackPanel content = (StackPanel) item.Content; content.Children.RemoveAt(content.Children.Count - 1); } } }
      
    <UserControl xmlns:layoutToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Layout.Toolkit"  x:Class="SilverlightApplication1.MainPage"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"	
                 	Width="640" Height="480" VerticalContentAlignment="Stretch">
        <Grid x:Name="LayoutRoot" Background="White">
            <layoutToolkit:Accordion x:Name="accordion" Width="100" BorderBrush="Black" Margin="5" >
                <layoutToolkit:AccordionItem Header="Header" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch"  >
                    <StackPanel Background="#FFD8D8D8" VerticalAlignment="Top">
                        <TextBlock Text="Content 1" />
                        <TextBlock Text="Content 2" />
                        <TextBlock Text="Content 3" />
                    </StackPanel>
                </layoutToolkit:AccordionItem>
                <layoutToolkit:AccordionItem Header="Header" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" >
                    <StackPanel Background="#FFD8D8D8" VerticalAlignment="Top">
                        <TextBlock Text="Content 1" />
                        <TextBlock Text="Content 2" />
                        <TextBlock Text="Content 3" />
                    </StackPanel>
                </layoutToolkit:AccordionItem>
                <layoutToolkit:AccordionItem Header="Header" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" >
                    <StackPanel Background="#FFD8D8D8" VerticalAlignment="Top">
                        <TextBlock Text="Content 1" />
                        <TextBlock Text="Content 2" />
                        <TextBlock Text="Content 3" />
                    </StackPanel>
                </layoutToolkit:AccordionItem>
                <layoutToolkit:AccordionItem Header="Header" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" >
                    <StackPanel Background="#FFD8D8D8" VerticalAlignment="Top">
                        <TextBlock Text="Content 1" />
                        <TextBlock Text="Content 2" />
                        <TextBlock Text="Content 3" />
                    </StackPanel>
                </layoutToolkit:AccordionItem>
            </layoutToolkit:Accordion>
            <Button x:Name="add" VerticalAlignment="Top" Content="Remove Content" Margin="110,5,0,0" HorizontalAlignment="Left" Click="remove_Click"/>
            <Button x:Name="remove" VerticalAlignment="Top" Content="Add Content" Margin="110,33,0,0" HorizontalAlignment="Left" Click="add_Click"/>
        </Grid>
    </UserControl>

     Hope this helps! :)

     

    Nic

    Friday, August 07, 2009 6:25 AM
  •  Nic - thanks for you post. I used your idea to create a static method to update the item's size. The slight bounce is tolerable.

     

    public static class AccordionItemExtensions
    {
    /// <summary>
    /// Forces a selected AccordionItem to resize to its contents.
    /// Doesn't work for Accordion.SelectionModes: One, OneOrMore
    /// </summary>
    /// <param name="item">Selected AccordionItem to udpate.</param>

    public static void UpdateSize(this AccordionItem item)
    {
    if (!item.IsLocked && item.IsSelected)
    {
    item.IsSelected = false;
    EventHandler updated = null;
    updated = delegate
    {
    item.LayoutUpdated -= updated;
    item.IsSelected = true;
    };
    item.LayoutUpdated += updated;
    }
    }
    }

     (Note - I think the bounce could be fixed by suspending animation during the update, but I haven't looked into it)

    John

    Monday, August 10, 2009 4:00 PM
  •  Here's an updated version for SL 3 that uses the new VisualTreeExtensions.InvokeOnLayoutUpdated.

     

        public static class AccordionItemExtensions
        {
            /// <summary>
            /// Forces a selected AccordionItem to resize to its contents.
            /// Doesn't work for Accordion.SelectionModes: One, OneOrMore
            /// </summary>
            /// <param name="item">Selected AccordionItem to udpate.</param>
            public static void UpdateSize(this AccordionItem item)
            {
                item.Dispatcher.BeginInvoke(
                    delegate
                    {
                        if (!item.IsLocked && item.IsSelected)
                        {
                            item.IsSelected = false;
                            item.InvokeOnLayoutUpdated(delegate { item.IsSelected = true; });
                        }
                    });
            }
        }
    
     
    
      John
    Friday, September 04, 2009 4:24 PM
  •   I also ran into this issue with the Accordion as well as another.  Not only does it not resize properly when the content changes size, it does not properly calculate the desired size for the content based on its own available size during layout.  I have made some modifications to the source for the June 2009 release of the toolkit which has gotten my app to an acceptable spot with the Accordion, and I figured I would share the edits here.  No warranty explicit or implied, etc, etc.

     To get the Accordion to allow items to resize I Modified AccordionItem so that it checks once an expansion animation is completed, in which it modifies the width or height of an ExpandableContentControl via its Percentage dependency property, whether or not the TargetSize for the ECC is actually on "Auto", and if so it sets the appropriate value back.  Replace the existing OnStoryboardFinished method with the following  (I apologize code formatting is currently disabled on the site and I am not going to bother with HTML):



    private void OnStoryboardFinished(object sender, EventArgs e)
            {
                _isBusyWithAction = false;

                if (ParentAccordion != null)
                {
                    ParentAccordion.OnActionFinish(this);
                }

                if (IsSelected)
                {
                    if (ExpandSite.RevealMode == ExpandDirection.Down || ExpandSite.RevealMode == ExpandDirection.Up)
                    {
                        if (double.IsNaN(ExpandSite.TargetSize.Height))
                        {
                            // we just animated the height of an expandsite that wants to autosize, so allow it to again.
                            ExpandSite.Height = double.NaN;
                        }
                    }
                    else if (ExpandSite.RevealMode == ExpandDirection.Left || ExpandSite.RevealMode == ExpandDirection.Right)
                    {
                        if (double.IsNaN(ExpandSite.TargetSize.Width))
                        {
                            // we just animated the width of an expandsite that wants to autosize, so allow it to again.
                            ExpandSite.Width = double.NaN;
                        }
                    }
                }
            }

     

    The second fix to get the Accordion to properly animate the items during expansion with correct sizes involves changing the way the ExpandableContentControl calculates its desired content size.  Previously it would allow its ExpandSite (ContentPresenter) to calculate its desired size based on an available size of Infinity in either axis if the TargetSize property was set to Auto.  However this allowed the ExpandSite to think it had as much room in either axis as it needed to fully layout its items, which is often not the case.  The desired content size now takes into account the RevealMode and if the ECC is set to expand down/up the desired content size clamps on the available width, likewise for left/right the desired content height clamps on the available height.  Here is the edited code in ExpandableContentControl.cs:

     internal Size CalculateDesiredContentSize(Size availableSize)
            {
                Size desiredSize = TargetSize;

                if(desiredSize.Width.Equals(Double.NaN))
                {
                    if(RevealMode == ExpandDirection.Down || RevealMode == ExpandDirection.Up )
                    {
                        desiredSize.Width = availableSize.Width;
                    }
                    else
                    {
                        desiredSize.Width = Double.PositiveInfinity;
                    }
                }

                if (desiredSize.Height.Equals(Double.NaN))
                {
                    if (RevealMode == ExpandDirection.Left || RevealMode == ExpandDirection.Right)
                    {
                        desiredSize.Height = availableSize.Height;
                    }
                    else
                    {
                        desiredSize.Height = Double.PositiveInfinity;
                    }
                }

                return desiredSize;
            }

     and:

     

    protected override Size MeasureOverride(Size availableSize)
            {
                // this control will always follow the TargetSize
                // and allow its content to take all the space it needs

                if (ContentSite != null)
                {
                    // we will adhere to the available size, to allow scrollbars
                    // to appear               
                    Size desiredSize = availableSize;

                    if (Percentage != 1)
                    {
                        // we shall use the targetsize, to allow the content
                        // to adjust to the final size it should be.
                        desiredSize = CalculateDesiredContentSize(availableSize);
                    }

                    MeasureContent(desiredSize);
                    return ContentSite.DesiredSize;
                }
                return new Size(0, 0);
            }

     

    Combined with this edit in AccordionItem.cs:

     private void OnExpandSiteContentSizeChanged(object sender, SizeChangedEventArgs e)
            {
                // only needed if we are not currently already working on a transition
                // if a sizechange occurs during a transition, it is not possible
                // to distinquish between one triggered by the expand/collapse
                // storyboard, or one by the content itself.
                if (IsSelected && _isBusyWithAction == false)
                {
                    // only undertake this in a situation where the resized content
                    // can be shown, ie. in a non-fixed scenario.
                    if ((!ShouldFillWidth && e.PreviousSize.Width != e.NewSize.Width) ||
                        (!ShouldFillHeight && e.PreviousSize.Height != e.NewSize.Height))
                    {
                        // since size has changed, a fresh approach should be taken
                        ExpandSite.MeasureContent(ExpandSite.CalculateDesiredContentSize(e.NewSize));
                        ExpandSite.RecalculatePercentage(ExpandSite.TargetSize);
                        // schedule a resize to move to this new size
                        Schedule(AccordionAction.Resize);
                    }
                }
            }

     

    Again I apologize for the formatting and length of this post, but hopefully the content is worthwhile.  These edits should allow the control to animate and resize correctly with no "jittering".

     

    Cheers.

     

    -Casey

    Thursday, September 17, 2009 7:28 PM
  • The easiest way for me to workaround it was to change a little ExpandableContentControl.MeasureContent from:
     

    internal void MeasureContent(Size desiredSize) {
        if (ContentSite != null) {
            ContentSite.Measure(desiredSize);
        }
    }
    
    to something like this:
     
    internal void MeasureContent(Size desiredSize) {
        if (ContentSite != null) {
            if (RevealMode == ExpandDirection.Up || RevealMode == ExpandDirection.Down) {
                if (VerticalAlignment != VerticalAlignment.Stretch) {
                    ContentSite.Measure(new Size(desiredSize.Width, Double.PositiveInfinity));
                    return;
                }
            }
            else {
                if (HorizontalAlignment != HorizontalAlignment.Stretch) {
                    ContentSite.Measure(new Size(Double.PositiveInfinity, desiredSize.Height));
                    return;
                }
            }
            ContentSite.Measure(desiredSize);
        }
    }
    
    Monday, January 11, 2010 3:16 PM
  • casey.rayl said: Again I apologize for the formatting and length of this post, but hopefully the content is worthwhile.  These edits should allow the control to animate and resize correctly with no "jittering". 

     

    I have just downloaded the October 19th Source Code for the Silverlight Toolkit (Change Set 32933) and applied your changes to the accordion control and I can confirm that your solution provides an effective fix for the accordion problem.

    I chose to use the October source code rather than the newer November release since I was already using that code elsewhere in my project, so I'm not sure whether this change got incorporated into the November code?

    Can you confirm whether the fix will be / has already been incorporated into the official Silverlight Toolkit release, or will we need to continue to apply it manually?

    Wednesday, March 24, 2010 6:46 AM
  • I'm also seeing this issue in my project.

    Is there any solid fix to this annoying problem?

    Monday, April 19, 2010 2:55 PM
  • Hi, here is a note for the not so swift (like me)

    My example is for databound accordions

     I'm using Casey.rayls solution with the VisualTreeExtension.

     I create a class called AccordionItemExtension in my main Namesapce.

     Then create a method like:
     

       private void FixAccordionContentSize()
    {

    foreach (var container in TimerList.Items)
    {
    AccordionItem item = TimerList.ItemContainerGenerator.ContainerFromItem(container) as AccordionItem;


    AccordionItemExtensions.UpdateSize(item);
    }

    }
     

    Which I call whenever I add or remove items from the ObservableCollection that the Accordion content is databound to..

    Works ok. Not noticeable really. A good enough solution for my needs.

     
      private void Clicked_AddListItem(object sender, RoutedEventArgs e)
    {

    // Assuming CoOrdList is our databound ObservableCollecton
    CoOrdList.Add(new Something());
    // Fix that pesky content resizing
    FixAccordionContentSize();

    }
     

    Hope this helps someone.

     

    Sunday, April 25, 2010 9:16 AM
  • I have the same problem, but don't have an easy place to tie in results. My accordion has a number of TextBox controls that are all multi-line and expand dynamically as the user types additional lines (and the screen width is changed, etc). The growth of one earlier in the structure is causing the others to be pushed out of view, and none of the Stretch ideas are working. Is there an easy workaround that doesn't involve tying in to events on every one of my controls?

    Thursday, May 20, 2010 2:50 PM
  • I had this working with the casey.rayl solution using modified Silverlight 3 Toolkit dlls, but when I upgraded to the Silverlight 4 Toolkit I was dismayed to find that the problem has come back, so MS don't appear to have fixed this yet. I thought this would be ancient history by now!

    I know you Silverlight guys are working very hard and creating lots of wonderful new stuff - which is a lot more fun than fixing bugs (features??), I suppose - but a little bit of time spent mending things like this would really be appreciated.

    Wednesday, June 02, 2010 5:30 AM
  • I had this working with the casey.rayl solution using modified Silverlight 3 Toolkit dlls, but when I upgraded to the Silverlight 4 Toolkit I was dismayed to find that the problem has come back, so MS don't appear to have fixed this yet. I thought this would be ancient history by now!

    I know you Silverlight guys are working very hard and creating lots of wonderful new stuff - which is a lot more fun than fixing bugs (features??), I suppose - but a little bit of time spent mending things like this would really be appreciated.


    Just ran into this again. Hope this is fixed in *crosses fingers* August Toolkit.

    Monday, August 09, 2010 11:25 PM
  • Another way of working around the issue, without modifying the AccordianItem.IsSelected property, and therefore triggering the SelectionChanged event, is to do the same thing that the Accordion does under the covers to animate the expanding/collapsing of its content: adjust the 'Percentage' DependencyProperty of the AccordionItem's nested ExpandableContentControl control. The 'Percentage' property specifies the amount (from 0 to 1) of content that is visible.

        public static class AccordionItemExtensions
        {
            /// <summary>
            /// Forces a selected AccordionItem to resize to its contents.
            /// </summary>
            /// <param name="item">Selected AccordionItem to udpate.</param>
            public static void UpdateSize(this AccordionItem item)
            {
                var expandableContentControl = item.GetVisualDescendants().OfType<ExpandableContentControl>().FirstOrDefault();
                if (expandableContentControl != null)
                {
                    var currentPercentage = expandableContentControl.Percentage;
                    expandableContentControl.Percentage = 0;
                    expandableContentControl.UpdateLayout();
                    expandableContentControl.Percentage = currentPercentage;
                }
            }
        }


    Friday, December 03, 2010 2:23 AM
  • Hi all.

    This is my solution:

    	/// <summary>
    	/// Доработаный класса AccordionItem, изменяет свой размер при изменении размера содержимого.
    	/// </summary>
    	public class MyAccordionItem : AccordionItem
    	{
    		/// <summary>
    		/// Флаг автоматического изменения размера по горизонтали в зависимости от размера содержимого.
    		/// </summary>
    		public static readonly DependencyProperty HorizontalAutoSizeProperty;
    
    		/// <summary>
    		/// Флаг автоматического изменения размера по вертикали в зависимости от размера содержимого.
    		/// </summary>
    		public static readonly DependencyProperty VerticalAutoSizeProperty;
    
    		/// <summary>
    		/// Статический конструктор используется для инициализации любых статических данных 
    		/// или для выполнения определенного действия, которое требуется выполнить только один раз. 
    		/// Он вызывается автоматически перед созданием первого экземпляра или ссылкой на какие-либо статические члены.
    		/// </summary>
    		static MyAccordionItem()
    		{
    			HorizontalAutoSizeProperty = DependencyProperty.Register(
    				"HorizontalAutoSize",
    				typeof(bool), 
    				typeof(MyAccordionItem),
    				new PropertyMetadata(false));
    
    			VerticalAutoSizeProperty = DependencyProperty.Register(
    				"VerticalAutoSize",
    				typeof(bool), 
    				typeof(MyAccordionItem),
    				new PropertyMetadata(false));
    		}
    
    		/// <summary>
    		/// Создает новый экземпляр класса MyAccordionItem
    		/// </summary>
    		public MyAccordionItem()
    			: base()
    		{
    			var contentElement = this.Content as FrameworkElement;
    			if (contentElement != null)
    			{
    				contentElement.SizeChanged += new SizeChangedEventHandler(this.ContectSizeChanged);
    			}
    		}
    
    		/// <summary>
    		/// Возвращает или устанавливает флаг автоматического изменения размера по горизонтали в зависимости от размера содержимого.
    		/// </summary>
    		public bool HorizontalAutoSize
    		{
    			get { return (bool)GetValue(HorizontalAutoSizeProperty); }
    			set { SetValue(HorizontalAutoSizeProperty, value); }
    		}
    
    		/// <summary>
    		/// Возвращает или устанавливает флаг автоматического изменения размера по вертикали в зависимости от размера содержимого.
    		/// </summary>
    		public bool VerticalAutoSize
    		{
    			get { return (bool)GetValue(VerticalAutoSizeProperty); }
    			set { SetValue(VerticalAutoSizeProperty, value); }
    		}
    
    		/// <summary>
    		/// Обработчик изменения свойства Content.
    		/// </summary>
    		/// <param name="oldContent">Старое значение.</param>
    		/// <param name="newContent">Новое значение.</param>
    		protected override void OnContentChanged(object oldContent, object newContent)
    		{
    			base.OnContentChanged(oldContent, newContent);
    			var oldContentElement = oldContent as FrameworkElement;
    			if (oldContentElement != null)
    			{
    				oldContentElement.SizeChanged -= this.ContectSizeChanged;
    			}
    
    			var newContentElement = newContent as FrameworkElement;
    			if (newContentElement != null)
    			{
    				newContentElement.SizeChanged += this.ContectSizeChanged;
    			}
    		}
    
    		/// <summary>
    		/// Обработчик изменения размера внутренего содержимого.
    		/// </summary>
    		/// <param name="sender">Источник события.</param>
    		/// <param name="e">Аргумент события.</param>
    		private void ContectSizeChanged(object sender, SizeChangedEventArgs e)
    		{
    			var expandableContentControl = this.GetVisualDescendants().OfType<ExpandableContentControl>().FirstOrDefault();
    			var senderElement = sender as FrameworkElement;
    			if (expandableContentControl != null && senderElement != null)
    			{
    				if (this.VerticalAutoSize)
    				{
    					expandableContentControl.Height = e.NewSize.Height + senderElement.Margin.Bottom + senderElement.Margin.Top;
    				}
    
    				if (this.HorizontalAutoSize)
    				{
    					expandableContentControl.Width = e.NewSize.Width + senderElement.Margin.Left + senderElement.Margin.Right;
    				}
    			}
    		}
    	}


    Wednesday, January 12, 2011 9:19 AM
  • If anyone is looking System.Linq is need for the above code

    Wednesday, January 26, 2011 9:41 PM
  • Just in case anyone is wondering, Casey's solution still (mostly) works in SL4.

    The only problem I'm having is that removing an AccordionItem collapses any remaining AccordionItems. I can live with that for the time being. When I resolve that, I will update this post.

    Thanks, Casey!

    Sunday, April 24, 2011 2:25 AM
  • xx

    Friday, March 09, 2012 5:21 AM
  • i am facing this issue in SL5, is there any solution for this in SL5?
    Tuesday, July 08, 2014 6:07 AM