【发布时间】:2010-12-01 07:16:10
【问题描述】:
我正在编写的代码是 WPF 应用程序的一部分,该应用程序应显示一组可供用户交互的扑克牌。所以我正在使用三个用户控件:
- 主控件
- CardStackControl
- 卡片控制
在 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}"
>
主视图模型:
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; }
// ...
卡片视图模型:
/// <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 时,用户控件不显示,并且没有任何测试数据可见。我使用this tutorial 作为指导,因此 MainViewModel 对应于该窗口中选项卡式控件上的“工作区”ViewModel。当然,这个例子应该水平布局每个控件,这现在很好 - 我还在学习 WPF。
显然,我已经在 .xaml 文件和其他脚手架代码中省略了代码生成的标签(如果从这些示例中不清楚,我可以修改它以发布该代码)。我现在只测试/绑定到 Model 类的字符串属性。
【问题讨论】:
标签: c# wpf xaml binding wpf-controls