[英]Dynamically add TextBlock to StackPanel
因此,我正在使用MVVM模式在C#中開發Windows Phone 8應用程序。 我有一個屏幕,其中的布局需要像這樣:
因此,我一直試圖在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>
現在一切正常,除了我列表中的部分說“如果button.count的動態列表大於1,請在此處插入TextBlock”。
讓我嘗試進一步解釋。 我的{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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.