gpt4 book ai didi

c# - 将 TextBlock 动态添加到 StackPanel

转载 作者:行者123 更新时间:2023-12-03 10:36:17 25 4
gpt4 key购买 nike

所以我正在使用 MVVM 模式在 C# 中开发一个 Windows Phone 8 应用程序。我有一个屏幕,布局需要是这样的:

  • 文本 block
  • 图片
  • 文本 block
  • 文本 block
  • 如果buttons.count 的动态列表> 1,则在此处插入一个TextBlock
  • 按钮动态列表
  • 文本 block
  • 文本 block

  • 所以我一直试图在 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>

    现在一切正常,除了我列表中显示“如果buttons.count的动态列表> 1在此处插入一个TextBlock”的部分。

    让我试着进一步解释一下。我的 {Binding RelatedLinks}绑定(bind)到 ObservableCollection<RelatedLink>在哪里 RelatedLink是一个有两个字符串的对象 HrefText .

    所以 if my ObservableCollection of RelatedLinks is bigger then 1我想在此 ItemsControl 列表上方放置一个标题文本。我怎样才能做到这一点?

    最佳答案

    ObservableCollection实现 INotifyPropertyChanged并通知 Count 的更改,所以你可以绑定(bind)到它。显示或隐藏 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。

    关于c# - 将 TextBlock 动态添加到 StackPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26736354/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com