Page 1 of 1

Cast exception with ItemsControl

Posted: 16 Jun 2020, 19:02
by Thanatos
Hello,

I am stuck with a cast problem on two ItemsControl which have for ItemPanel a WrapPanel and a StackPanel.

Here is the code for the WrapPanel:
<ItemsControl x:Name="SessionsList" Style="{StaticResource SessionPanelStyle}">
	<!--GENERATED SESSION TILES HERE-->
</ItemsControl>
    <Style x:Key="SessionPanelStyle" TargetType="ItemsControl">
        <Setter Property="ItemsPanel">
            <Setter.Value>
                <ItemsPanelTemplate>
                    <WrapPanel Style="{DynamicResource TilesPanel}"/>
                </ItemsPanelTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="ItemTemplate">
            <Setter.Value>
                <DataTemplate>
                    <Border>
	                    ...
                    </Border>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
private ItemsControl SessionsList;

private void InitializeComponent()
{
	Noesis.GUI.LoadComponent(this, "Assets/WPF/File.xaml");
	
	SessionsList = (ItemsControl)FindName("SessionsList");;
}
public void FillSessionsList()
{
	SessionsList.Items.Clear();
	
	var tile = new SessionTile()
    	{
    		...
    	};
	
	SessionsList.Items.Add(tile);

}
And I got this when I launch it on Unity:
InvalidCastException: Specified cast is not valid.
Do you have an idea? Do you need more informations?

Thank you in advance!

Re: Cast exception with ItemsControl

Posted: 17 Jun 2020, 10:14
by Thanatos
Ok I found a solution: I took the ItemsControl parent and then removed the SessionList in the InitializeComponent to create the ItemControl directly into FillSessionsList and set the parent content with it, it worked!

Re: Cast exception with ItemsControl

Posted: 18 Jun 2020, 11:25
by sfernandez
Are you using NoesisGUI 3.0?
I'm not able to reproduce the cast exception if the named element type specified in the xaml corresponds to the one used in code. It shouldn't be necessary to create the ItemsControl in code.

Anyway, have you considered using bindings to populate the ItemsControl instead of directly accessing it from code?
You can define a ViewModel that exposes a SessionList observable collection property:
public class ViewModel
{
  public ObservableCollection<SessionTile> SessionList { get; private set; }
  public ViewModel() { SessionList = new ObservableCollection<SessionTile>(); }
}
Set that ViewModel as DataContext of your user control:
public YourUserControl: UserControl
{
  public YourUserControl()
  {
    InitializeComponent();
    
    DataContext = new ViewModel();
  }
  ...
}
And in xaml:
<ItemsControl ItemsSource="{Binding SessionList}" .../>

Re: Cast exception with ItemsControl

Posted: 06 Jul 2020, 10:49
by Thanatos
Sorry I didn't see you answered my topic!

Yes I'm using NoesisGUI 3.0. I will try your suggestion, thank you!