0

I'm trying to set a DataContext of a UserControl (Panel.xaml/PanelViewModel.cs) through a ListView of another control (PanelList.xaml/PanelListViewModel.cs).

I have the following ViewModel:

public class PanelListViewModel
    {
        public List<PanelViewModel> Apps { get; set; } = new List<PanelViewModel>
        {
            new PanelViewModel
            {
                ApplicationName = "App 1",
                ApplicationVersion = "v. 1.0.3",
                IsInstalled = true
            },
            new PanelViewModel
            {
                ApplicationName = "App 2",
                ApplicationVersion = "v. 1.0.3",
                IsInstalled = false
            }
        };
    }

And have the following UserControl:

<UserControl.DataContext>
    <vm:PanelListViewModel/>
</UserControl.DataContext>

<ListView ItemsSource="{Binding Apps}">

        <ListView.ItemTemplate>

            <DataTemplate>

                    <local:Panel DataContext="{Binding}"
                                           VerticalAlignment="Center"
                                           HorizontalAlignment="Center"/>

            </DataTemplate>

        </ListView.ItemTemplate>

    </ListView>

It works at first in the designer preview window in VS, but as soon as I build it, the DataContext Binding doesn't work anymore. Please help :)

  • You should generally never explicitly set the DataContext of a UserControl. Assuming you did that for your Panel control (similar to how you it for PanelList), `DataContext="{Binding}` will not do what you expect. Besides that, the expression `DataContext="{Binding}"`is always redundant. – Clemens Feb 28 '22 at 15:53
  • @Clemens what you said did the trick. I wasn't aware that they conflict between them. I'm new at this, how can I mark your comment as the answer? – Martin Kjortoshev Mar 01 '22 at 08:15
  • This is a common problem, because there are so many "tutorials" on the internet that propagate this programming error. I have marked the question as duplicate. – Clemens Mar 01 '22 at 08:21
  • Also note that there is no reason to use ListView, unless you set its View property. Otherwise use the simpler base class ListBox. – Clemens Mar 01 '22 at 08:25

1 Answers1

-1

Can you set a "x:Name" for the ListView and try the following code in the load event, maybe that helps:

C# Code:

myListView.DataContext = Apps;

XAML Code:

<ListView ItemsSource="{Binding Apps}" x:Name="MyListView">
  • Thanks for the response, but this doesn't work as well. The ListView DataContext is correctly set, but the ListView item is a custom UserControl and here is where I want to set the DataContext – Martin Kjortoshev Feb 28 '22 at 14:43
  • `myListView.DataContext = Apps;` in conjunction with `ItemsSource="{Binding Apps}"` makes no sense. – Clemens Feb 28 '22 at 15:56