WPF - 绑定列表框列表<字符串> - 我究竟做错了什么?列表、错了、字符串、绑定

2023-09-04 06:43:45 作者:可遇不可求

我试图做一些很基本的在这里,这是我不会期望给我这么多的问题。我有一个公共的财产我叫ITEMLIST主窗口类是类型名单,其中,串> 。我添加到整个项目的生命这份名单中,并希望ListBox控件我有我的形式,当我添加新的项目到ITEMLIST属性自动更新。

I'm trying to do something very basic here, something I wouldn't have expected to give me this many problems. I have a public property on my main Window class called ItemList which is of type List<string>. I add to this list throughout the life of the program, and would like the ListBox control I have on my form to automatically update when I add new items to the ItemList property.

到目前为止,我有以下的XAML:

So far, I have the following XAML:

<Window x:Class="ElserBackupGUI.Main"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Backup Profile Editor [New Profile]" Height="480" Width="640">
    <DockPanel>
        <Menu DockPanel.Dock="Top">
            <MenuItem Header="File">
                <MenuItem Header="Open"/>
            </MenuItem>
        </Menu>
        <StackPanel Orientation="Vertical" DockPanel.Dock="Top" Margin="10 10 10 3">
            <TextBlock>Items to backup:</TextBlock>
        </StackPanel>
        <DockPanel DockPanel.Dock="Bottom" Margin="10 0 10 10">
            <StackPanel Orientation="Horizontal">
                <Button Name="AddDirectoryButton" Height="22.725" Width="120" Margin="0 0 6 0" Click="AddDirectoryButton_Click">Add Directory...</Button>
                <Button Name="AddFileButton" Height="22.725" Width="90" Margin="0 0 6 0" Click="AddFileButton_Click">Add File...</Button>
                <Button Name="RemoveDirectoriesButton" Height="22.725" Width="75.447" Margin="0 0 6 0">Remove</Button>
            </StackPanel>
        </DockPanel>
        <ListBox Name="SelectedItems" Margin="10 0 10 10" ItemsSource="{Binding Path=ItemList}"/>
    </DockPanel>
</Window>

相关code-背后code是这样的:

The relevant code-behind code looks like:

public partial class Main : Window
{
    private string _lastFolder = string.Empty;
    private ObservableCollection<string> _itemList = new ObservableCollection<string>();

    public ObservableCollection<string> ItemList {
        get { return _itemList ?? (_itemList = new ObservableCollection<string>()); }
        set { _itemList = value; }
    }

    public Main()
    {
        InitializeComponent();
        ItemList.Add("test item");
        DataContext = this;
    }

    private void AddDirectoryButton_Click(object sender, RoutedEventArgs e)
    {
        FolderBrowserDialog dialog = new FolderBrowserDialog();
        if (!string.IsNullOrEmpty(_lastFolder))
            dialog.SelectedPath = _lastFolder;

        if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            _lastFolder = dialog.SelectedPath;
            ItemList.Add(dialog.SelectedPath);
        }
    }

    private void AddFileButton_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog dialog = new OpenFileDialog();
        if (!string.IsNullOrEmpty(_lastFolder))
            dialog.InitialDirectory = _lastFolder;

        if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            _lastFolder = System.IO.Path.GetDirectoryName(dialog.FileName);
            SelectedItems.ItemsSource = null;
            ItemList.Add(dialog.FileName);
        }
    }
}

我是比较新的WPF和大多数的教程似乎过于复杂,这样一个简单的问题。我似乎无法得到任何地方在这里 - 我缺少什么

I'm relatively new to WPF and most of the tutorials seem overly complicated for such a simple problem. I can't seem to get anywhere here - what am I missing?

推荐答案

您应该使用 的BindingList&LT; T&GT; 或ObservableCollection<T>而不是名单,其中,T&GT;

的问题在于,用于结合工作,你想要的方式,它需要执行INotifyCollectionChanged或IBindingList. 名单,其中,T&GT; 不支持此

The problem is that, for binding to work the way you want, it needs to implement INotifyCollectionChanged or IBindingList. List<T> does not support this.

编辑:

审核更改后,仍有一个问题。

After reviewing your changes, there is still one problem.

在AddFileButton_Click事件处理程序,删除以下行:

In the AddFileButton_Click event handler, remove the following line:

SelectedItems.ItemsSource = null;

有明确移除你的绑定,并造成列表框中清除。如果删除,你的code应该原样。

It is explicitly removing your binding, and causing the list box to clear. If you remove that, your code should work as-is.

不过,我建议改变你的集合定义和构造更多的东西,如:

However, I do recommend changing your collection definition and constructor to something more like:

    // No need for the null checking every time, or public setter.  They just cause issues
    public ObservableCollection<string> ItemList
    {
        get;
        private set;
    }

    // Add construction here, now that we're using an auto-prop
    public Main()
    {
        this.ItemList = new ObservableCollection<string>();
        InitializeComponent();
        ItemList.Add("test item");
        DataContext = this;
    }