我正在处理的代码是 WPF应用程序的一部分,该应用程序应该显示一组用户可以与之交互的扑克牌堆栈.所以我正在使用三个UserControl: MainControl CardStackControl CardControl 在MainControl.xaml中:
> MainControl
> CardStackControl
> CardControl
在MainControl.xaml中:
<StackPanel Grid.Row="0" Orientation="Horizontal"> <ItemsControl ItemsSource="{Binding Path=CardStacks}" > <ItemsPanelTemplate> <StackPanel Orientation="Horizontal" /> </ItemsPanelTemplate> </ItemsControl> </StackPanel>
我的数据模板在Resources.xaml文件中定义:
<DataTemplate x:Key="MainTemplate" DataType="{x:Type ViewModel:MainViewModel}"> <View:MainControl /> </DataTemplate> <DataTemplate DataType="{x:Type ViewModel:CardStackViewModel}"> <View:CardStackControl /> </DataTemplate> <DataTemplate x:Key="CardTemplate" DataType="{x:Type ViewModel:CardViewModel}"> <View:CardControl /> </DataTemplate>
CardStackControl.xaml:
<StackPanel Orientation="Vertical"> <TextBlock Height="30" HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding Path=CardName}" /> <ItemsControl Height="Auto" ItemsSource="{Binding Path=Cards}" ItemTemplate="{StaticResource CardTemplate}" > <ItemsPanelTemplate> <StackPanel Orientation="Horizontal" /> </ItemsPanelTemplate> </ItemsControl> <TextBlock Height="30" HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding Path=Count}" /> </StackPanel>
CardControl.xaml:
<TextBlock Name="TitleTextBlock" Grid.Row="0" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding Path=Name}" >
MainViewModel:
public ObservableCollection<CardStackViewModel> CardStacks; // ...
CardStackViewModel:
public class CardStackViewModel { private CardStack Model; public string CardName { get { return this.Model.CardType.Name; } } public int Count { get { return this.Model.Cards.Count; } } public ObservableCollection<CardViewModel> Cards { get; private set; } // ...
CardViewModel:
/// <summary> /// A reference to the Card type. /// </summary> private Card Model; /// <summary> /// Retrieves the name of the card. /// </summary> public string Name { get { return this.Model.CardType.Name; } } public string Caption { get { return this.Model.CardType.Text; } } // ...
在MainViewModel,CardStackViewModel构造函数中,两个ObservableCollection实例都被初始化,填充并填充了一些测试数据.
当我加载应用程序并创建MainViewModel时,UserControls不会显示,并且没有任何测试数据可见.我使用this tutorial作为指南,因此MainViewModel对应于该窗口中选项卡式控件上的“Workspaces”ViewModel.当然,这个例子应该横向布局每个控件,现在这很好 – 我还在学习WPF.
显然,我已经在.xaml文件和其他脚手架代码中省略了代码生成的标签(如果从这些示例中不清楚,我可以修改它以发布该代码).我现在只测试/绑定到Model类的字符串属性.
声明ItemsPanelTemplate的方式不正确:您将其声明为ItemsControl的项目.你应该这样做:<ItemsControl ItemsSource="{Binding Path=CardStacks}" > <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Horizontal" IsItemsHost="True" /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> </ItemsControl>