如何使用Listbox进行自定义控制?

kla*_*dos 0 vb.net wpf xaml

在此输入图像描述

我想用自定义项目模板制作水平列表框,所以我做了一个基本的模板.

但是,我找不到将"事物"绑定到WPF XAML的示例,尤其是列出了填充了自定义项的列表框.

我只是想用Image,Label,Combobox动态添加/删除列表框中的项目,之前填充的数字为1到10.

ADD/REMOVE按钮将放置在WPF控件之外,这意味着按钮将位于主窗口窗体上.

此外,主窗口窗体中有文本框和图片选择器,以便我可以更改文本和图像.

以下是XAML背后的代码:

Public Class listSequence

Public Sub New()

    InitializeComponent()

    listbox.Items.Add("hi")
    listbox.Items.Add("there")

End Sub
End Class
Run Code Online (Sandbox Code Playgroud)

以下是XAML:

<ListBox Name="listbox" VerticalContentAlignment="Stretch"  ScrollViewer.VerticalScrollBarVisibility="Disabled" ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.CanContentScroll="True" >
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" VerticalAlignment="Stretch"  />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Border Padding="10" Margin="5" BorderThickness="1" BorderBrush="Aqua" CornerRadius="0" Width="120" VerticalAlignment="Stretch">
                <StackPanel>
                    <Image />
                    <Label Content="{Binding}" />   
                    <TextBlock Text="hi" />
                    <ComboBox x:Name="cboRepeat" ItemsSource="{Binding}" DisplayMemberPath="RepeatCounter" IsSynchronizedWithCurrentItem="True"/>
                </StackPanel>
            </Border>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

She*_*dan 6

说你找不到一个绑定'事物'到WPF XAML的例子,特别是对于填充了自定义项目列表框 '并没有说明你的搜索能力... MSDN 充满了它们.你似乎只是缺少一些基本的WPF知识......看看这个例子.

假设我们有一个名为的基本类Item:

public class Item : INotifyPropertyChanged
{
    public string Text { get; set; } // Implement INotifyPropertyChanged 
    public string ImagePath { get; set; } // properly on these properties
}
Run Code Online (Sandbox Code Playgroud)

以及视图模型中的这些集合:

public ObservableCollection<Item> Items { get; set; } 
Run Code Online (Sandbox Code Playgroud)

现在要在UI中显示这些项目,我们使用a ListBox并设置ItemsSource属性:

<ListBox ItemsSource="{Binding Items}">
</ListBox>
Run Code Online (Sandbox Code Playgroud)

在定义时ListBox.ItemTemplate,您需要了解这DataTemplate将应用于每个项目,并且它可以访问Item类中定义的所有属性:

<ListBox ItemsSource="{Binding Items}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <Image ImageSource="{Binding ImagePath}" />
                <TextBlock Text="{Binding Text}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

因此,您可以访问集合类中的属性,如上所示.您可以通过查看MSDN 上的" ItemsControl.ItemTemplate属性"页面找到完整的故事.