【问题标题】:从 WPF 中的列表框中获取项目并写入其他列表
【发布时间】:2022-01-22 19:15:30
【问题描述】:

我在 Wpf 中使用 Itemtemplate 和 Datatemplate 创建了一个列表框:

<ListBox Name="LBox" HorizontalContentAlignment="Stretch" Grid.Column="2" SelectionMode="Single">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>
                        <TextBlock x:Name="LTxtBox" Text="{Binding NAME}" Grid.Column="0"/>
                        <ProgressBar x:Name="PBarLbox" Grid.Column="1" Minimum="0" Maximum="100" Value="{Binding FORTSCHRITT}" />
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

我可以在我的列表框中添加/更改/删除项目。

现在我尝试将项目保存在 txt 文件中。 如果我添加一个项目,它运行良好,我可以将它们保存在我的 txt 文件中。

现在我尝试在我的列表框中保存更改,但我如何才能访问我的列表框中的项目? .

这是我的可观察列表和属性类的代码。

private ObservableCollection<TodoItem> Todo =new ObservableCollection<TodoItem>();
    public class TodoItem : INotifyPropertyChanged
    {
        public string NAME { get; set; }
        public int FORTSCHRITT{ get; set; }
         //###########################################
        public string Name
        {
            get { return this.NAME; }
            set
            {
                if (this.NAME != value)
                {
                    this.NAME = value;
                    this.NotifyPropertyChanged("NAME");
                }
            }
        }
        public int fortschritt
        {
            get { return this.FORTSCHRITT; }
            set
            {
                if (this.FORTSCHRITT != value)
                {
                    this.FORTSCHRITT = value;
                    this.NotifyPropertyChanged("FORTSCHRITT");
                }
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }

我的想法是,如果我要关闭我的窗口,请用列表框中的新更改项覆盖旧列表。

为此我创建了一个窗口关闭事件:

void DataWindow_Closing(object sender, CancelEventArgs e)
    {  // TODO
       // Wenn er das Fenster schließt soll er alle Daten die im ToDo Fenster sind speichern und die alte Datei Überschreiben.
       
    }

我尝试过使用 For each 来获得访问权限,我尝试过 for 循环但我无法获得访问权限。

与:

List<string> list = new List<string>();
            string[] arr;
            foreach (var x in LBox.Items) 
            {
                list.Add(x.ToString());
            }
            arr= list.ToArray();
            string display=String.Join(Environment.NewLine, arr);
            MessageBox.Show(display);

我可以看到他可以访问这些项目,但他打印了以下内容: enter image description here

如何打印正确的值?

【问题讨论】:

  • 我没有真正看到您的问题,您正在成功获取您的物品。您是否正在寻找如何覆盖 ToString() 使其不打印类型? toDoWpf.MainWindow+TodoItem ? - docs.microsoft.com/en-us/dotnet/api/system.object.tostring
  • 您的 ObservableCollection 与 ListBox 有什么关系?通常将 ListBox.ItemsSource 绑定到集合。这样您只需保存/加载集合,而无需触摸 ListBox。
  • 双重成员NAME/Name或FORTSCHRITT/fortschritt背后的任何原因?好像错了。
  • 为什么不枚举 Todo 集合呢?您无需访问控件。现在您可以访问每个单独的 TodoItem,您可以通过引用属性来构造字符串。或覆盖 TodoItem.ToString 以返回有用的字符串表示形式。
  • 如果您需要在多个步骤中构造字符串,也可以将数组和列表替换为 StringBuilder。

标签: c# wpf listbox


【解决方案1】:

您不应访问控件来获取数据项。而是直接访问源集合:

MainViewModel.cs

class MainViewModel : INotifyPropertyChanged
{
  public ObservableCollection<TodoItem> TodoItems { get; }

  public MainViewModel()
  {
    this TodoItems = new ObservableCollection<TodoItem>();
  }

  public async Task SaveDataAsync()
  {
    var fileContentBuilder = new StringBuilder();
    foreach (TodoItem todoItem in TodoItems)
    {
      fileContentBuilder.AppendLine($"{todoItem.Name}, {todoItem.Fortschritt}");
    }

    await using var destinationFileStream = File.Open("Destination_File_Path", FileMode.Create);
    await using var streamWriter = new StreamWriter(destinationFileStream);
    string fileContent = fileContentBuilder.ToString();
    await streamWriter.WriteAsync(fileContent);
  }
}

MainWindow.xaml.cs

public partial class MainWindow : Window
{
  private MainViewModel MainVieModel { get; }

  public MainWindow()
  {
    InitilaizeComponent();

    this.MainViewModel = new MainViewModel();
    this.DataContext = this.MainViewModel;
    this.Closing += SaveDataToFile_OnClosing;
  }

  private async void SaveDataToFile_OnClosing(object sender, CancelEventArgs e)
    => await this.MainViewModel.SaveDataAsync();
}

MainWindow.xaml

<Window>
  <ListBox itemsSource="{Binding TodoItems}">
    ...
  </ListBox>
</Window>

C# 中的属性必须如下所示(注意正确的大小写:字段使用 camelCase,所有其他成员使用 PascalCase)。还可以使用nameof 指定属性名称:

private int fortschritt;
public int FortSchritt
{
  get => this.fortschritt; 
  set
  {
    if (value != this.fortschritt)  
    {
      this.fortschritt = value;
      this.NotifyPropertyChanged(nameof(this.Fortschritt));
    }
  }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-10-20
  • 2013-04-07
  • 2017-06-09
  • 2019-06-03
  • 1970-01-01
  • 2011-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多