c# - 在 XAML 中将 ListBox 绑定(bind)到列表(集合)

标签 c# wpf xaml wpf-controls binding

我正在学习 WPF,所以我在这方面有点菜鸟。 我看到了一些关于如何做我想做的事情的例子,但没有任何确切的...

问题:我想将 List 绑定(bind)到 ListBox。我想在 XAML 中完成它,而无需在代码中进行编码。我怎样才能做到这一点?

现在我那样做:

XAML

<ListBox x:Name="FileList">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Label Content="{Binding Path=.}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

代码隐藏

public MainWindow()
{
    // ...
    files = new List<string>();
    FileList.ItemsSource = files;
}

private void FolderBrowser_TextChanged(object sender, RoutedEventArgs e)
{
    string folder = FolderBrowser.Text;
    files.Clear();
    files.AddRange(Directory.GetFiles(folder, "*.txt", SearchOption.AllDirectories));
    FileList.Items.Refresh();
}

但我想摆脱 C# 代码中的 FileList.ItemsSource = files;FileList.Items.Refresh();

谢谢

最佳答案

首先,在列表框中设置绑定(bind):

<ListBox x:Name="FileList" ItemsSource="{Binding Files}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Label Content="{Binding Path=.}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

<ListBox x:Name="FileList" ItemsSource="{Binding Files}" DisplayMemberPath="."/>

接下来,确保"file"是您的 DataContext(或隐藏代码)中的一个属性。 (您不能绑定(bind)到字段,只能绑定(bind)到属性...)

理想情况下,您需要将文件设为 ObservableCollection<T> 而不是 List<T> ,还有。这将允许绑定(bind)正确处理添加或删除元素。

如果你做了这两件事,它应该会正常工作。

关于c# - 在 XAML 中将 ListBox 绑定(bind)到列表(集合),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2678419/

相关文章:

c# - 比较两个xml文件并显示差异

c# - ObserveOnDispatcher 不调用 UI 线程中的处理程序

c# - Windows 7 更新,导致 WPF 应用程序中出现 "Item has already been added. Key in dictionary: controlbrush"

c# - 如何在实例化大量控件时不阻塞 UI

C#、WPF、将 List<string> 绑定(bind)到 DataGrid

javascript - 在下拉列表更改时调用 Javascript 函数

c# - 在 C# 中附加事件处理程序的两种不同方式是否存在实际差异?

c# - 如何在业务层实现审计

c# - Windows 10 通用应用程序中的滚动查看器有问题吗?

c# - 如何解决 XAML 解析错误?