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 :)
CodePudding user response:
Maybe this helps:
<ListView ItemsSource="{Binding Apps}">
<ListView.ItemTemplate>
<DataTemplate>
<local:Panel DataContext="{Binding RelativeSource={RelativeSource AncestorType=ListView},Path=ItemsSource}"
VerticalAlignment="Center"
HorizontalAlignment="Center"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
or
DataContext="{Binding RelativeSource={RelativeSource AncestorType=ListView},Path=DataContext.Apps}"
CodePudding user response:
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">