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

时间:2014-01-06 04:06:33

标签: wpf vb.net visual-studio

enter image description here

我想制作带有自定义项目模板的水平列表框,因此我制作了一个基本模板。

然而,我无法找到一个绑定事物的例子。到那个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

以下是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>

1 个答案:

答案 0 :(得分: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
}

在视图模型中收集这些内容:

public ObservableCollection<Item> Items { get; set; } 

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

<ListBox ItemsSource="{Binding Items}">
</ListBox>

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

Item

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