将ListBox绑定到XAML中的List(Collection)

Dav*_*vid 7 c# wpf xaml binding wpf-controls

我正在学习WPF,所以我对此非常感兴趣.我看到了一些关于如何做我想做的事的例子,但没有确切的......

问题:我想将List绑定到ListBox.我想在XAML中完成它,没有编码后面的代码.我怎样才能做到这一点?

现在我做的那样:

XAML

<ListBox x:Name="FileList">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Label Content="{Binding Path=.}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

代码背后

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();
}
Run Code Online (Sandbox Code Playgroud)

但我想摆脱FileList.ItemsSource = files;,并FileList.Items.Refresh();在C#代码.

谢谢

Ree*_*sey 19

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

<ListBox x:Name="FileList" ItemsSource="{Binding Files}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Label Content="{Binding Path=.}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

要么

<ListBox x:Name="FileList" ItemsSource="{Binding Files}" DisplayMemberPath="."/>
Run Code Online (Sandbox Code Playgroud)

接下来,确保"Files"是DataContext(或后面的代码)中的属性.(您不能绑定到字段,只能绑定属性...)

理想情况下,您也希望将文件设为一个ObservableCollection<T>而不是一个List<T>.这将允许绑定正确处理添加或删除元素.

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