简体   繁体   English

从WPF中的列表框中读取项目

[英]Read item from listbox in WPF

I have listbox in WPF C# which contains some entries. 我在WPF C#中有一个列表框,其中包含一些条目。 Out of those entries, I'll update only single entry. 在这些条目中,我将仅更新单个条目。 What I want is, When I click on "Done Editing" button, I want to read only the updated(whose text changed) entry instead of all other entries. 我想要的是,当我单击“完成编辑”按钮时,我只想读取更新的(其文本已更改)条目,而不是所有其他条目。

My entry name is "Harvest_TimeSheetEntry". 我的输入名称是“ Harvest_TimeSheetEntry”。 I tried below line, but it reads all the entries. 我在下面的行中尝试过,但它会读取所有条目。

Harvest_TimeSheetEntry h = listBox1.SelectedItem as Harvest_TimeSheetEntry;

Any idea? 任何想法?

I prefer to address the problem by using the SelectedItem property of a ListBox or CurrentItem of a DataGrid and bind it to a property in my ViewModel. 我更喜欢通过使用ListBox的SelectedItem属性或DataGrid的CurrentItem解决问题,并将其绑定到ViewModel中的属性。

<ListBox ItemsSource="{Binding HarvestTimeSheet}" SelectedItem={Binding CurrentEntry}.../>

<Button Content="Done Editing..." Command="{Binding DoneEditingCommand}"/>

In my ViewModel I have 在我的ViewModel中

    private Harvest_TimeSheetEntry _currentHarvest_TimeSheetEntry;
    public Harvest_TimeSheetEntry CurrentHarvest_TimeSheetEntry
    {
        get { return _currentHarvest_TimeSheetEntry; }
        set
        {
            if (_currentHarvest_TimeSheetEntry == value) return;
            _currentHarvest_TimeSheetEntry = value;
            RaisePropertyChanged("CurrentHarvest_TimeSheetEntry");
        }
    }

This is set to the selected item in the ListBox. 这设置为列表框中的选定项目。

My ViewModel provides the code for the button. 我的ViewModel提供了按钮的代码。 I'm using MVVM light to easily provide the RelayCommand and RaisePropertyChanged. 我正在使用MVVM指示灯轻松提供RelayCommand和RaisePropertyChanged。

    private RelayCommand _doneEditingCommand;
    public RelayCommand DoneEditingCommand
    {
        get { return _doneEditingCommand ?? (_doneEditingCommand = new RelayCommand(HandleDoneEditing, () => true)); }
        set { _doneEditingCommand = value; }
    }

    public void HandleDoneEditing()
    {
        if (CurrentHarvest_TimeSheetEntry != null)
            //Do whatever you need to do.
    }

It's a little more work but you get so much control and flexibility over the flow. 要做更多的工作,但是您对流程有很多控制和灵活性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM