在 ItemsControl 中添加 TextBlock

Adding TextBlock in ItemsControl

我想使用 Caliburn micro 在我的 ItemsControl 中添加带有文本的 TextBlock 到我的 DataTemplate

<ItemsControl x:Name="Images"  Grid.Column="1" Grid.ColumnSpan="3">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid Rows="1"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid Height="180" Width="180" Margin="10">
                    <TextBlock Text="{Binding Names}"/>
                    <Grid.Background>
                        <ImageBrush Stretch="Uniform" ImageSource="{Binding}" 
                            ViewboxUnits="RelativeToBoundingBox"    
                            local:ViewBoxTracking.Source="{Binding ElementName=MainImage}" />
                    </Grid.Background>
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

我的 C# 来自 ViewModel class 的代码如下所示:

    public ObservableCollection<ImageSource> Images { get; set; } = new ObservableCollection<ImageSource>();
    public ObservableCollection<string> Names { get; set; } = new ObservableCollection<string>();

    this.Names.Add("text1");
    this.Names.Add("text2");
    this.Names.Add("text3");
    this.NotifyOfPropertyChange(() => this.Names);

    this.Images.Add(bmpimage1);
    this.Images.Add(bmpimage2);
    this.Images.Add(bmpimage3);
    this.NotifyOfPropertyChange(() => this.Images);

上面的代码没有出现:

我想以编程方式将 TextBlocks 附加到 Images。我希望它看起来像这样:

如何使用 Caliburn.Micro 的绑定将 TextDataTemplateItemsControl 添加到 TextBlocks

您应该使用单一来源集合。 Images 应该 return 一个 ObservableCollection<YourType> 其中 YourType 有一个 ImageSource 属性 一个 string 属性。 YourType 可能是自定义 class 或 Tuple<string, ImageSource>:

public ObservableCollection<Tuple<string, ImageSource>> Images { get; set; } = new ObservableCollection<Tuple<string, ImageSource>>();
...
this.Images.Add(Tuple.Create("text1", bmpimage1));
this.NotifyOfPropertyChange(() => this.Images);

然后您可以绑定到 ItemTemplate:

中的两个属性
<TextBlock Text="{Binding Item1}"/>

<TextBlock x:Name="Item1"/>

如果您使用的是 Caliburn Micro,那么您应该考虑 "buying in" 基于约定的绑定机制。 https://caliburnmicro.com/documentation/conventions

这将为您即时创建绑定。

对于命名控件,它会在数据上下文中查找具有匹配名称的 属性,并在该控件的默认值 属性 上创建绑定。

文本块将是文本,我认为图像是图像源。

因此具有 public 属性的 class 比元组代码更少。因为我认为这不适用于元组。

如果您使用 rowviewmodels 的 observablecollection,其中 rowviewmodel 是具有 public 属性 Img 和 Txt 的 class,则以下简化标记:

    <StackPanel>
        <Image Name="Img"/>
        <TextBlock Name="Txt"/>
    </StackPanel>

只要您实现了 Caliburn micro 的预期部分,就应该看到图像和文本块绑定。

同样,您collection的itemssource的绑定。