【发布时间】:2018-05-29 14:50:59
【问题描述】:
我正在尝试创建一个 WPF 应用程序,其中有一个显示帐户列表的 StackPanel。每个账户的代码中都有一个 Account 对象,存储在 List 结构中。我想将此数据绑定到我的 WPF,但我不想要一个列表框。
相反,我为每个帐户摘要的显示方式定义了一个模板。然后,我想将这些堆叠在 StackPanel 中并收工。
问题是数据绑定只从列表中获取第一项,仅此而已。如何绑定它,以便有效地创建一个格式良好的数据块的小堆叠列表?
这是相关的 WPF 代码:
<StackPanel Name="sp_AccountList" Margin="0,0,0,0" VerticalAlignment="Top">
<StackPanel.Resources>
<svc:AccountBalanceColorConverter x:Key="accountColorConverter" />
<Style x:Key="AccountSummaryBackgroundGradient" TargetType="{x:Type StackPanel}">
<!-- nice formatting code here -->
</Style>
<Style x:Key="AccountSummaryNameStyle" TargetType="{x:Type TextBlock}">
<Setter Property="Padding" Value="10,0,0,0" />
<Setter Property="FontSize" Value="18" />
<Setter Property="Height" Value="20" />
<Setter Property="FontFamily" Value="Cambria" />
<Setter Property="Foreground" Value="White" />
<Setter Property="Background" Value="Transparent" />
</Style>
<Style x:Key="AccountSummaryBalanceStyle" TargetType="{x:Type TextBlock}">
<Setter Property="Padding" Value="10,0,0,0" />
<Setter Property="FontSize" Value="14" />
<Setter Property="Height" Value="20" />
<Setter Property="FontFamily" Value="Cambria" />
<Setter Property="Background" Value="Transparent" />
</Style>
<ObjectDataProvider x:Key="accounts"
ObjectType="{x:Type svc:AccountService}"
MethodName="ListAccounts" />
<DataTemplate x:Key="AccountSummaryLayout">
<StackPanel Orientation="Vertical" Style="{StaticResource AccountSummaryBackgroundGradient}">
<TextBlock Text="{Binding Path=Name}" Style="{StaticResource AccountSummaryNameStyle}" />
<StackPanel Orientation="Horizontal">
<TextBlock Foreground="{Binding Path=TotalAccountBalance, Converter={StaticResource accountColorConverter} }" Text="{Binding Path=TotalAccountBalance, Mode=OneWay}" Style="{StaticResource AccountSummaryBalanceStyle}" />
<TextBlock Foreground="{Binding Path=AvailableAccountBalance, Converter={StaticResource accountColorConverter} }" Text="{Binding Path=AvailableAccountBalance, Mode=OneWay}" Style="{StaticResource AccountSummaryBalanceStyle}" />
</StackPanel>
</StackPanel>
</DataTemplate>
</StackPanel.Resources>
<StackPanel Orientation="Vertical">
<ContentPresenter x:Name="AccountSummaryPresenter" ContentTemplate="{StaticResource AccountSummaryLayout}" Content="{DynamicResource accounts}" />
</StackPanel>
</StackPanel>
【问题讨论】:
-
几个cmets:我创建了一个类AccountService,它的方法ListAccounts() 返回一个List
结构。我已经确认这个函数正在正确地生成一个列表。
标签: wpf data-binding datatemplate