将TextBlock动态添加到StackPanel
本文关键字:StackPanel 添加 动态 TextBlock | 更新日期: 2023-09-27 18:29:14
所以我正在使用MVVM模式在C#中开发一个Windows Phone 8应用程序。我有一个屏幕,那里的布局需要像这样:
- 文本块
- 图像
- 文本块
- 文本块
- 如果按钮计数的动态列表>1,请在此处插入文本块
- 按钮的动态列表
- 文本块
- 文本块
所以我一直试图在xaml代码中设置它,它看起来像这样:
<StackPanel Orientation="Vertical">
<TextBlock Margin="20,0,20,0" TextWrapping="Wrap" Foreground="#c8d75a" Text="{Binding Title, Mode=TwoWay}" Height="46"></TextBlock>
<Image Margin="20,0,20,0" Source="{Binding ImageLink}" Height="200"></Image>
<TextBlock Margin="20,0,20,0" TextWrapping="Wrap" Foreground="#7e9d83" Text="{Binding subTitle, Mode=TwoWay}" Height="46"></TextBlock>
<TextBlock Margin="20,0,20,0" TextWrapping="Wrap" Foreground="#7e9d83" Text="{Binding Description, Mode=TwoWay}" Height="46"></TextBlock>
<ItemsControl ItemsSource="{Binding RelatedLinks}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Margin="20,0,20,0" Foreground="#c8d75a" Text="{Binding Text, Mode=TwoWay}" Height="46">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Tap">
<cm:ActionMessage MethodName="OpenLink">
<cm:Parameter Value="{Binding Href}"></cm:Parameter>
</cm:ActionMessage>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBlock>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<TextBlock Margin="20,0,20,0" TextWrapping="Wrap" Foreground="#7e9d83" Text="{Binding Creator, Mode=TwoWay}" Height="46"></TextBlock>
<TextBlock Margin="20,0,20,0" TextWrapping="Wrap" Foreground="#7e9d83" Text="{Binding PubDate, Mode=TwoWay}" Height="46"></TextBlock>
现在,除了我的列表上写着"如果按钮计数的动态列表>1,请在此处插入一个文本块"的部分外,一切都正常工作。
让我试着进一步解释一下。我的{Binding RelatedLinks}
是到ObservableCollection<RelatedLink>
的绑定,其中RelatedLink
是具有两个字符串Href
和Text
的对象。
所以if my ObservableCollection of RelatedLinks is bigger then 1
我想在这个ItemsControl列表上方放置一个标题文本。我怎样才能做到这一点?
ObservableCollection
实现INotifyPropertyChanged
并通知对Count
的更改,因此您可以绑定到它。要显示或隐藏TextBlock
,您可以如下更改其Visibility
:
<TextBlock
Visibility="{Binding RelatedLinks.Count, Converter={StaticResource CountToVisibilityConverter}}"
... />
剩下的就是编写CountToVisibilityConverter并将其添加到资源中。它的Convert
方法类似于:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (int)value > 1 ? Visibility.Visible: Visibility.Collapsed;
}
另一种方法是将属性bool TextVisible
添加到ViewModel中,并在每次更新ObservableCollection时对其进行更新,然后使用标准的BoolToVisibilityConverter。