正如标题所述,我尝试从2个不同的ViewModel中获取数据,但是上面没有显示任何内容。我做错了吗?
这是我的XAML
<Window.DataContext>
<local:VMContainer/>
</Window.DataContext>
<Grid>
<StackPanel Orientation="Horizontal">
<ItemsControl ItemsSource="{Binding Path=VM1.LibraryVM1}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Image Width="150" Height="200" Source="{Binding Path=cover}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ItemsControl ItemsSource="{Binding Path=VM2.LibraryVM2}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Image Width="150" Height="200" Source="{Binding Path=cover}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Grid>
我的容器
public class VMContainer
{
public VModel1 VM1 { get; set; }
public VModel2 VM2 { get; set; }
}
ViewModel 1
public class VModel1
{
public DataView LibraryVM1 { get; private set; }
public VModel1()
{
DataTable vm1 = new DataTable();
using (MySqlConnection connection = new MySqlConnection("SERVER=localhost;" + "DATABASE=library;" + "UID=root;" + "PASSWORD=;"))
{
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = new MySqlCommand("Select * from index_movie_list", connection);
adapter.Fill(vm1);
}
LibraryVM1 = vm1.DefaultView;
}
}
ViewModel 2
public class VModel2
{
public DataView LibraryVM2 { get; private set; }
public VModel2()
{
DataTable vm2 = new DataTable();
using (MySqlConnection connection = new MySqlConnection("SERVER=localhost;" + "DATABASE=library;" + "UID=root;" + "PASSWORD=;"))
{
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = new MySqlCommand("Select * from index_tv_list", connection);
adapter.Fill(vm2);
}
LibraryVM2 = vm2.DefaultView;
}
}
当我运行程序时,它仅显示空白白色。当我在没有容器的情况下更改它并选择1 ViewModel时,仅显示图像,但无法查看ViewModel2。有解决方案吗?
编辑:由于Loocid
的回答,我初始化了VM1和VM2之后解决了问题。
答案 0 :(得分:2)
您的VMContainer
不会初始化VModel1
和VModel2
,因此您将绑定到null
。
尝试一下:
public class VMContainer
{
public VModel1 VM1 { get; set; } = new VModel1();
public VModel2 VM2 { get; set; } = new VModel2();
}