Home > Enterprise >  MVVM How to pass object in Itemscontrol
MVVM How to pass object in Itemscontrol

Time:10-14

Is there any way to bind whole object while generating list by itemscontrol? MainWindowViewModel.cs

   private List<TrackModel> _trackModels=new List<TrackModel>();

    public List<TrackModel> TrackModels
    {
        get { return _trackModels; }
        set { _trackModels = value; }
    }

MainWindow.Xaml

<ItemsControl ItemsSource="{Binding TrackModels}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Label Content="{Binding TrackModel}"/> <!--Here should be my UserControl-->
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

The thing is that I want to create my own UserControl that will receive TrackModel instance because I will need it to get FileName of track to play music. Is there any way to pass TRACKMODEL to my UserControl while using ItemsControl?

CodePudding user response:

You do not need more than this:

<ItemsControl ItemsSource="{Binding TrackModels}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <local:YourUserControl/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

It requires that YourUserControl does not explicitly set its own DataContext property, but instead simply binds its child elements to the automatically provided DataContext object, which is a TrackModel element from the TrackModels collection.

CodePudding user response:

There is another option if you wanted to explore it though it maps to the same property.

If you give your ItemsControl an x:Name property such as myitems you will be able to access the ItemsSource property from the code behind and set the content there.

  • Related