簡體   English   中英

動態添加TextBlock到StackPanel

[英]Dynamically add TextBlock to StackPanel

因此,我正在使用MVVM模式在C#中開發Windows Phone 8應用程序。 我有一個屏幕,其中的布局需要像這樣:

  • TextBlock的
  • 圖片
  • TextBlock的
  • TextBlock的
  • 如果buttons.count的動態列表大於1,請在此處插入一個TextBlock
  • 動態按鈕列表
  • TextBlock的
  • TextBlock的

因此,我一直試圖在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是一個具有兩個字符串HrefText的對象。

因此, 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM