none
Silverlight Layout states beforeloaded -> afterloaded transition just not working

    General discussion

  • Hello there

    I am trying to add a initial animation when items are added to a list box. For this I'm using Layoutstates, generated by blend inside the itemcontainerstyle:

    <VisualStateGroup x:Name="LayoutStates">
        <VisualStateGroup.Transitions>
            <VisualTransition GeneratedDuration="0:0:0.2"/>
        </VisualStateGroup.Transitions>
        <VisualState x:Name="AfterLoaded"/>
        <VisualState x:Name="BeforeLoaded">
            <Storyboard>
                <DoubleAnimation Duration="0" To="35" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateY)" Storyboard.TargetName="grid" d:IsOptimized="True"/>
                <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="grid" d:IsOptimized="True"/>
            </Storyboard>
        </VisualState>
        <VisualState x:Name="BeforeUnloaded">
            <Storyboard>
                <DoubleAnimation Duration="0" To="0.85" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.ScaleX)" Storyboard.TargetName="grid" d:IsOptimized="True"/>
                <DoubleAnimation Duration="0" To="0.85" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.ScaleY)" Storyboard.TargetName="grid" d:IsOptimized="True"/>
                <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="grid" d:IsOptimized="True"/>
            </Storyboard>
        </VisualState>
    </VisualStateGroup>

    my listbox looks like this:

    <ListBox Grid.Row="1" ItemsSource="{Binding Days}" x:Name="Days"
                        HorizontalAlignment="Stretch"
                        SelectedItem="{Binding CurrentDay, Mode=TwoWay}" 
                        ItemTemplate="{StaticResource TimeRecordByDayItemTemplate}" 
                        ItemsPanel="{StaticResource ByMonthDaysItemsPanelTemplate}"
                        ScrollViewer.HorizontalScrollBarVisibility="Disabled" 
                        ItemContainerStyle="{StaticResource DayListBoxItemStyle}" />

    I just don't get any animation even though i was just following the channel 9 tutorials step by step!

    This is the first problem with my state manager, I am also encountering problems with datatriggers, that should go to a state when certain conditions are met, where some do work and some do not, but all of my bindings are correct! Also all the animations do work in Expression Blend preview.

    I can't make out the problem, I've had this so often with silverlight and animations copied from the simplest samples not working in the own environment...

    Thanks for your help!

    (Also posted this question here: http://stackoverflow.com/questions/6862917/silverlight-layout-states-beforeloaded-afterloaded-transition-just-not-working )

    Thursday, July 28, 2011 1:51 PM

All replies

  • Hi,

    I just don't get any animation even though i was just following the channel 9 tutorials step by step!

    I am trying to add a initial animation when items are added to a list box.

    According to your code and description ,I would like to suggest you to follow the tips below to make the sample project work as you want.

    Create a new project in Microsoft Expression Blend4.

    1. Create a ListBox control in the MainPage.xaml.(Just Drag the control to the LayoutRoot). Set its name as listbox1.

    2. Create two buttons(Add and Remove) besides the ListBox control.(Just Drag the controls to the LayoutRoot).

    3.Add Click event for the buttons which are mentioned above.

    Code in MainPage.xaml.cs file:

     public partial class MainPage : UserControl
            {
                public MainPage()
                {
                    // Required to initialize variables
                    InitializeComponent();
                }
    
                private void AddNewItem(object sender, System.Windows.RoutedEventArgs e)
                {
                    this.listbox1.Items.Insert(0, "New Item" + this.listbox1.Items.Count);
                }
    
                private void RemoveItem(object sender, System.Windows.RoutedEventArgs e)
                {
                    if (this.listbox1.Items.Count > 0)
                    {
                        this.listbox1.Items.RemoveAt(0);
                    }
                }
            }

    4. Right click the ListBox control and select Edit Additional Templates -> Edit Layout of Item(ItemPanel) -> Create Empty.

    5. Drag a FluidMoveBehavior from Assets Panel(Behaviors) to StackPanel(of the ItemPanelTemplate which is created above).

    6. In the Properties window of the FluidMoveBehavior ,set AppliesTo as Children in common properties tag.

    7. Back to the Listbox control , Right click the ListBox control and select Edit Additional Templates -> Edit Generated Item Container(ItemContainerStyle) -> Edit a Copy .

    8. Find LayoutStates tag in the States panel, click BeforeLoaded. Then in properties window of the Gird, set RenderTransform X as (-400) in Transform tag.

    9.Find LayoutStates tag in the States panel, click BeforeUnLoaded. Then in properties window of the Gird, set RenderTransform X as (400) in Transform tag.

    10. Find LayoutStates tag in the States panel, set Default transition as 0.5s.

    11. Run the application(F5) and see the result.

    In addition ,you can also download the working sample project(LayoutStates.zip) which is created at my side. Please check it and see whether it helps.

    Hope it can help you.

    Tuesday, August 02, 2011 5:10 AM
  • Hi

    Thank you for the answer.

    Those are the steps I followed, unfortunately they don't seem to work on my listbox.

    [deleted stuff]

    EDIT: I see now what might be the problem.

    My list is not actually dynamic, theres always the same number of items, and i am never adding or removing items but just initializing the collection at creation time.

    This is as it should be, but the layout states system will only transition items that have been added or removed afterwards the initialization it seems.

    I can archieve the effect when im doing a foreach on my items and adding them to my collection, so instead of:

    Items = new ObservableCollection<object>() { "Johnny", "Thommy", "Jay", "Wommy" };

    I do something like this:

    Items = new ObservableCollection<object>() ;
    foreach (var item in new[]{ "Johnny", "Thommy", "Jay", "Wommy" })
    {
        Items.Add(item);
    }

    Also note that the DataContext needs to be set(obviously)

    Here is a sample of at which point the transition will work:

    public MainPage()
    {
    	//No transition
    	Items = new ObservableCollection<object>(new []{"John", "Tom", "Mom"});
    
    	//No transition either
    	Items.Add("Johnny");
    
    	InitializeComponent();
    
    	//nope
    	Items.Add("Thommy");
    
    	listbox1.DataContext = this;
    
    	//here it is the layout transition!
    	Items.Add("Mummy");
    }

    But unfortunately this only works after the DataContext has been set, but the architecture I use sets the datacontext after the viewmodel has been initialized, and I am not so sure it would be good to change that(maybe I need to?).

    Now I could set a delay for filling the collection or something, this obviously is not a valid solution, as I am depending upon the collection being filled right from the constructor and not using a timer or stuff(bad style anyway).

    How to archieve this transition upon creation of the collection, or maybe on setting the itemssource of the listbox? 

    Thanks!

    Thursday, August 04, 2011 4:54 AM
  • Hi,

    Those are the steps I followed, unfortunately they don't seem to work on my listbox.

    I have modified your code as below, it works fine at my side now ,please check it and see whether it helps.

    1.Code in silverlight (.xaml file):

    <UserControl x:Class="LayoutStates.MainPage"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    	xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:Layout="http://schemas.microsoft.com/expression/2010/interactions" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
        d:DesignHeight="300" d:DesignWidth="400">
        <UserControl.Resources>
            <Style x:Key="DaysListBoxItemStyle" TargetType="ListBoxItem">
                <Setter Property="Padding" Value="3"/>
                <Setter Property="HorizontalContentAlignment" Value="Left"/>
                <Setter Property="VerticalContentAlignment" Value="Top"/>
                <Setter Property="Background" Value="Transparent"/>
                <Setter Property="BorderThickness" Value="1"/>
                <Setter Property="TabNavigation" Value="Local"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ListBoxItem">
                            <Grid x:Name="grid" Background="{TemplateBinding Background}" RenderTransformOrigin="0.5,0.5">
                                <Grid.RenderTransform>
                                    <CompositeTransform/>
                                </Grid.RenderTransform>
                                <VisualStateManager.VisualStateGroups>
                                    <VisualStateGroup x:Name="CommonStates">
                                        <VisualState x:Name="Normal"/>
                                        <VisualState x:Name="MouseOver">
                                            <Storyboard>
                                                <DoubleAnimation Duration="0" To=".35" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="fillColor"/>
                                            </Storyboard>
                                        </VisualState>
                                        <VisualState x:Name="Disabled">
                                            <Storyboard>
                                                <DoubleAnimation Duration="0" To=".55" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="contentPresenter"/>
                                            </Storyboard>
                                        </VisualState>
                                    </VisualStateGroup>
                                    <VisualStateGroup x:Name="SelectionStates">
                                        <VisualState x:Name="Unselected"/>
                                        <VisualState x:Name="Selected">
                                            <Storyboard>
                                                <DoubleAnimation Duration="0" To=".75" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="fillColor2"/>
                                            </Storyboard>
                                        </VisualState>
                                    </VisualStateGroup>
                                    <VisualStateGroup x:Name="FocusStates">
                                        <VisualState x:Name="Focused">
                                            <Storyboard>
                                                <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetProperty="Visibility" Storyboard.TargetName="FocusVisualElement">
                                                    <DiscreteObjectKeyFrame KeyTime="0">
                                                        <DiscreteObjectKeyFrame.Value>
                                                            <Visibility>Visible</Visibility>
                                                        </DiscreteObjectKeyFrame.Value>
                                                    </DiscreteObjectKeyFrame>
                                                </ObjectAnimationUsingKeyFrames>
                                            </Storyboard>
                                        </VisualState>
                                        <VisualState x:Name="Unfocused"/>
                                    </VisualStateGroup>
                                    <VisualStateGroup x:Name="LayoutStates">
                                        <VisualStateGroup.Transitions>
                                            <VisualTransition GeneratedDuration="0:0:0.3"/>
                                        </VisualStateGroup.Transitions>
                                        <VisualState x:Name="AfterLoaded"/>
                                        <VisualState x:Name="BeforeLoaded">
                                            <Storyboard>
                                                <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateX)" Storyboard.TargetName="grid" d:IsOptimized="True"/>
                                                <DoubleAnimation Duration="0" To="25" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateY)" Storyboard.TargetName="grid" d:IsOptimized="True"/>
                                            </Storyboard>
                                        </VisualState>
                                        
                                        <!--I add the code as below to your page-->
                                        <VisualState x:Name="BeforeUnloaded">
                                            <Storyboard>
                                                <DoubleAnimation Duration="0" To="400" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateY)" Storyboard.TargetName="grid" d:IsOptimized="True"/>
                                            </Storyboard>
                                        </VisualState>
                                        <!---->
                                        
                                    </VisualStateGroup>
                                </VisualStateManager.VisualStateGroups>
                                <Rectangle x:Name="fillColor" Fill="#FFBADDE9" IsHitTestVisible="False" Opacity="0" RadiusY="1" RadiusX="1"/>
                                <Rectangle x:Name="fillColor2" Fill="#FFBADDE9" IsHitTestVisible="False" Opacity="0" RadiusY="1" RadiusX="1"/>
                                <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}"/>
                                <Rectangle x:Name="FocusVisualElement" RadiusY="1" RadiusX="1" Stroke="#FF6DBDD1" StrokeThickness="1" Visibility="Collapsed"/>
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
            <ItemsPanelTemplate x:Key="ByMonthDaysItemsPanelTemplate">
                <StackPanel HorizontalAlignment="Stretch">
                    <i:Interaction.Behaviors>
                        <Layout:FluidMoveBehavior AppliesTo="Children"/>
                    </i:Interaction.Behaviors>
                </StackPanel>
            </ItemsPanelTemplate>
            <DataTemplate  x:Key="TimeRecordByDayItemTemplate">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="25"/>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="1*"/>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="1*"/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Column="0" Text="{Binding Day}" HorizontalAlignment="Left"/>
                </Grid>
            </DataTemplate>
        </UserControl.Resources>
        <Grid x:Name="LayoutRoot" Background="White">
            <ListBox  x:Name="listboxDays" Margin="0,21,146,24" Width="254" 
                      ItemsSource="{Binding}"
                        HorizontalAlignment="Stretch"  ItemTemplate="{StaticResource TimeRecordByDayItemTemplate}"  
                        ItemsPanel="{StaticResource ByMonthDaysItemsPanelTemplate}" 
                        ScrollViewer.HorizontalScrollBarVisibility="Disabled" ItemContainerStyle="{StaticResource DaysListBoxItemStyle}" />
            <Button Content="Add New Item" HorizontalAlignment="Right" Height="48" Margin="0,31,52,0" VerticalAlignment="Top" Width="88" Click="AddNewItem"/>
            <Button Content="Remove Item" HorizontalAlignment="Right" Height="44" Margin="0,109,52,0" VerticalAlignment="Top" Width="88" Click="RemoveItem"/>
        </Grid>
    </UserControl>
    

    2.Code in the silverlight page(.xaml.cs):

    namespace LayoutStates
    {
        public partial class MainPage : UserControl
        {
            public MainPage()
            {
                InitializeComponent();
                this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            }
    
            void MainPage_Loaded(object sender, RoutedEventArgs e)
            {
                // You can get the data from your own datasource
                // I get the datasource like this in order to run the sample more conveniently.
                this.listboxDays.DataContext = Days.GetData();
            }
            private void AddNewItem(object sender, System.Windows.RoutedEventArgs e)
            {
                Days d = new Days();
                d.Day = System.DateTime.Now.ToShortTimeString();
                ObservableCollection<Days> data = (ObservableCollection<Days>)listboxDays.DataContext;
                data.Add(d);
                this.listboxDays.DataContext = data;
            }
    
            private void RemoveItem(object sender, System.Windows.RoutedEventArgs e)
            {
                if (this.listboxDays.Items.Count > 0)
                {
                    Days d = (Days)this.listboxDays.Items[0];
                    ObservableCollection<Days> data = (ObservableCollection<Days>)listboxDays.DataContext;
                    data.Remove(d);
                    this.listboxDays.DataContext = data;
                }
    
                // If you want to remove the selected item of listbox control.
                // You can use the code as below:
    
                //Days d = (Days)this.listboxDays.SelectedItem;
                //ObservableCollection<Days> data = (ObservableCollection<Days>)listboxDays.DataContext;
                //data.Remove(d);
                //this.listboxDays.DataContext = data;
            }
        }
        public class Days
        {
            public string Day { get; set; }
            public static ObservableCollection<Days> GetData()
            {
                ObservableCollection<Days> data = new ObservableCollection<Days>();
                data.Add(new Days()
                {
                    Day = "Value1",
                });
                data.Add(new Days()
                {
                    Day = "Value2",
                });
                data.Add(new Days()
                {
                    Day = "Value3",
                });
                return data;
            }
        }
    
    }

    Hope it can help you.

    Thursday, August 04, 2011 5:47 AM
  • Thanks for your answer again, I really appreciate your efforts going trough my XAML! ;P

    But I found out the problem is, that the transition obviously doesn't apply upon creation of a list, only for operations on an list. See my edited post above for details.

    Thursday, August 04, 2011 5:58 AM
  • Hi,

    But unfortunately this only works after the DataContext has been set, but the architecture I use sets the datacontext after the viewmodel has been initialized, and I am not so sure it would be good to change that(maybe I need to?).

    From my experience ,you can first set an empty datasource for the DataContext of a ListBox control, then call a function to add the items to the empty datasource. In this way ,the transition will be shown.

    How to archieve this transition upon creation of the collection

    I would like to suggest you to check the sample below:

    1.Code in a silverlight page(.xaml file):

    <UserControl x:Class="LayoutStates.MainPage"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    	xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:Layout="http://schemas.microsoft.com/expression/2010/interactions" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
        d:DesignHeight="300" d:DesignWidth="400">
        <UserControl.Resources>
            <Style x:Key="DaysListBoxItemStyle" TargetType="ListBoxItem">
                <Setter Property="Padding" Value="3"/>
                <Setter Property="HorizontalContentAlignment" Value="Left"/>
                <Setter Property="VerticalContentAlignment" Value="Top"/>
                <Setter Property="Background" Value="Transparent"/>
                <Setter Property="BorderThickness" Value="1"/>
                <Setter Property="TabNavigation" Value="Local"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ListBoxItem">
                            <Grid x:Name="grid" Background="{TemplateBinding Background}" RenderTransformOrigin="0.5,0.5">
                                <Grid.RenderTransform>
                                    <CompositeTransform/>
                                </Grid.RenderTransform>
                                <VisualStateManager.VisualStateGroups>
                                    <VisualStateGroup x:Name="CommonStates">
                                        <VisualState x:Name="Normal"/>
                                        <VisualState x:Name="MouseOver">
                                            <Storyboard>
                                                <DoubleAnimation Duration="0" To=".35" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="fillColor"/>
                                            </Storyboard>
                                        </VisualState>
                                        <VisualState x:Name="Disabled">
                                            <Storyboard>
                                                <DoubleAnimation Duration="0" To=".55" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="contentPresenter"/>
                                            </Storyboard>
                                        </VisualState>
                                    </VisualStateGroup>
                                    <VisualStateGroup x:Name="SelectionStates">
                                        <VisualState x:Name="Unselected"/>
                                        <VisualState x:Name="Selected">
                                            <Storyboard>
                                                <DoubleAnimation Duration="0" To=".75" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="fillColor2"/>
                                            </Storyboard>
                                        </VisualState>
                                    </VisualStateGroup>
                                    <VisualStateGroup x:Name="FocusStates">
                                        <VisualState x:Name="Focused">
                                            <Storyboard>
                                                <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetProperty="Visibility" Storyboard.TargetName="FocusVisualElement">
                                                    <DiscreteObjectKeyFrame KeyTime="0">
                                                        <DiscreteObjectKeyFrame.Value>
                                                            <Visibility>Visible</Visibility>
                                                        </DiscreteObjectKeyFrame.Value>
                                                    </DiscreteObjectKeyFrame>
                                                </ObjectAnimationUsingKeyFrames>
                                            </Storyboard>
                                        </VisualState>
                                        <VisualState x:Name="Unfocused"/>
                                    </VisualStateGroup>
                                    <VisualStateGroup x:Name="LayoutStates">
                                        <VisualStateGroup.Transitions>
                                            <VisualTransition GeneratedDuration="0:0:0.5"/>
                                        </VisualStateGroup.Transitions>
                                        <VisualState x:Name="AfterLoaded" />
                                        <VisualState x:Name="BeforeLoaded">
                                            <Storyboard>
                                                <DoubleAnimation Duration="20.0:0:0" To="0" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateX)" Storyboard.TargetName="grid" d:IsOptimized="True"/>
                                                <DoubleAnimation Duration="0" To="150" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateY)" Storyboard.TargetName="grid" d:IsOptimized="True"/>
                                            </Storyboard>
                                        </VisualState>
    
                                        <VisualState x:Name="BeforeUnloaded">
                                            <Storyboard>
                                                <DoubleAnimation Duration="0" To="400" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateY)" Storyboard.TargetName="grid" d:IsOptimized="True"/>
                                            </Storyboard>
                                        </VisualState>
                                        
                                    </VisualStateGroup>
                                </VisualStateManager.VisualStateGroups>
                                <Rectangle x:Name="fillColor" Fill="#FFBADDE9" IsHitTestVisible="False" Opacity="0" RadiusY="1" RadiusX="1"/>
                                <Rectangle x:Name="fillColor2" Fill="#FFBADDE9" IsHitTestVisible="False" Opacity="0" RadiusY="1" RadiusX="1"/>
                                <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}"/>
                                <Rectangle x:Name="FocusVisualElement" RadiusY="1" RadiusX="1" Stroke="#FF6DBDD1" StrokeThickness="1" Visibility="Collapsed"/>
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
            <ItemsPanelTemplate x:Key="ByMonthDaysItemsPanelTemplate">
                <StackPanel HorizontalAlignment="Stretch">
                    <i:Interaction.Behaviors>
                        <Layout:FluidMoveBehavior AppliesTo="Children"/>
                    </i:Interaction.Behaviors>
                </StackPanel>
            </ItemsPanelTemplate>
            <DataTemplate  x:Key="TimeRecordByDayItemTemplate">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="25"/>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="1*"/>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="1*"/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Column="0" Text="{Binding}" HorizontalAlignment="Left"/>
                </Grid>
            </DataTemplate>
        </UserControl.Resources>
        <Grid x:Name="LayoutRoot" Background="White">
            <ListBox  x:Name="listboxDays" Margin="0,21,146,24" Width="400" 
                      ItemsSource="{Binding}"
                        HorizontalAlignment="Stretch"  ItemTemplate="{StaticResource TimeRecordByDayItemTemplate}"  
                        ItemsPanel="{StaticResource ByMonthDaysItemsPanelTemplate}" 
                        ScrollViewer.HorizontalScrollBarVisibility="Disabled" ItemContainerStyle="{StaticResource DaysListBoxItemStyle}" />
            <Button Content="Add New Item" HorizontalAlignment="Right" Height="48" Margin="0,31,52,0" VerticalAlignment="Top" Width="88" Click="AddNewItem"/>
            <Button Content="Remove Item" HorizontalAlignment="Right" Height="44" Margin="0,109,52,0" VerticalAlignment="Top" Width="88" Click="RemoveItem"/>
        </Grid>
    </UserControl>
    
    

    2.Code in the silverlight page(.xaml.cs file):

     public partial class MainPage : UserControl
        {
            public MainPage()
            {
                InitializeComponent();
                this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            }
            void MainPage_Loaded(object sender, RoutedEventArgs e)
            {
                ObservableCollection<object> data = new ObservableCollection<object>();
                this.listboxDays.DataContext = data;
                AddInitialData(data);
            }
    
            public void AddInitialData(ObservableCollection<object> data)
            {
                data.Add("John");
                data.Add("Tom");
                data.Add("Mom");
            }
    
            private void AddNewItem(object sender, System.Windows.RoutedEventArgs e)
            {
                string value = System.DateTime.Now.ToShortTimeString();
                ObservableCollection<object> data = (ObservableCollection<object>)listboxDays.DataContext;
                data.Add(value);
    
                this.listboxDays.DataContext = data;
            }
    
            private void RemoveItem(object sender, System.Windows.RoutedEventArgs e)
            {
                if (this.listboxDays.Items.Count > 0)
                {
                    object d = (object)this.listboxDays.Items[0];
                    ObservableCollection<object> data = (ObservableCollection<object>)listboxDays.DataContext;
                    data.Remove(d);
                    this.listboxDays.DataContext = data;
                }
    
            }
        }

    Hope it can help you.

    Friday, August 05, 2011 1:14 AM
  • Hello

    Since my ViewModel is fairly complex, im not able to set the datacontext before filling the list in this case.

    I think the Layoutstate transitions functionality is not exactly what I need after all, since I don't want the items to transition depending on operations on the itemssource, but actually only when an listbox item is created and removed on the UI(when the itemssource changes).

    So for this I think I only need AfterLoaded and BeforeUnloaded on the items. I did this with a custom control, something like specified here: http://xamlcoder.com/blog/2010/11/04/creating-a-metro-ui-style-control/

    This more or less works for Loaded, but not for Unload event unfortunately(The element propably gets unloaded before the animation starts). I think I'll give up, I wasted so much time trying to get some animations working...

     

    Friday, August 05, 2011 7:35 AM
  • Hi,

    I am trying to achieve the same behavious with a WPF Listbox and can't wget it to work since the templates are different.

    I know that your example works with silverlight and would like to ask you if you would be able to replicate the same thing with a small WPF control.

    Thanks for your great work and efforts.

    Tuesday, November 01, 2011 9:01 PM