【问题标题】:C#, WPF Bindingarray to ListBox won't WorkC#,WPF Bindingarray 到 ListBox 不起作用
【发布时间】:2019-11-12 19:38:40
【问题描述】:

我无法将数组绑定到 ListBox。

我在网上看了很多方法,但都没有成功。似乎数据显示在 ItemsSource 中,但未显示在列表框中。

代码:

public partial class MainWindow : ThemedWindow
{
    public string selectedItem { get; set; }
    public ObservableCollection<string> MyFiles { get; set; }
    public MainWindow()
    {   
        InitializeComponent();
        DataContext = this;
    }

    private void Button_Click(object sender,RoutedEventArgs e)
    {

        string[] filePaths = Directory.GetFiles(TextEdit.Text);
        MyFiles = new ObservableCollection<string>(filePaths);
        selectedItem = MyFiles[0];
        foreach (string filePath in filePaths)
        {
            Console.WriteLine(filePath);
            string file = Path.GetFileName(filePath);
            Console.WriteLine(file);
        }
    }
}  

XAML:

<ListBox x:Name="listBox"
            BorderThickness="2"
            Height="352"
            HorizontalAlignment="Center"
            ItemsSource="{Binding MyFiles}"
            Margin="92,0,95.6,10"
            SelectedItem="{Binding selectedItem, Mode=TwoWay}"
            SelectionMode="Single" 
            VerticalAlignment="Bottom"
            Width="606"
            />

没有错误消息只是不在列表框中显示输出

【问题讨论】:

  • 感谢您的意见。但是,我是一个业余爱好者,并没有理解它。

标签: c# data-binding listbox


【解决方案1】:

您的问题是绑定是在您创建实例之前完成的。

在声明中试试这个:

public ObservableCollection<string> MyFiles { get; } = new ObservableCollection<string>();

并替换:

MyFiles = new ObservableCollection<string>(filePaths);

与:

foreach(var file in filePaths)
    MyFiles.Add(file);

【讨论】:

    【解决方案2】:

    由于您在设置数据上下文后设置集合,因此您必须使用INotifyPropertyChanged 接口使您的属性MyFiles 可通知。

    或者,您只在构造函数中创建一次,然后,您只需添加或删除项目。使用集合的新实例设置属性会破坏绑定。

    【讨论】:

    • 谢谢。初学者没看懂。
    猜你喜欢
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多