且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用MVVM从列表框中删除选择的项目。

更新时间:2023-11-28 22:38:10

首先,你需要使用一个Collection类型,它将通知UI任何更改。所以:

  public   const   string  MyListPropertyName =   ListBox; 
private 列表< string> _listBox = null ;
public 列表< string> ListBox
{
get
{
return _listBox = _listBox ?? new List< string>();
}
set
{
if (_ listBox == value
{
return ;
}
RaisePropertyChanged(MyListPropertyName);
_listBox = value ;
RaisePropertyChanged(MyListPropertyName);
}
}



可以更改为:

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



你的XAML丢失所以我可以看看 SelectedItem 属性是否正确绑定。



我也无法检查你的 DeleteCommand 已正确启用。 RelayCommand 支持启用和禁用绑定按钮。所以你可以像以下一样连线:

  public  RelayCommand DeleteCommand {获得跨度>;  private   set ; } 

private void InitializeRelayCommands()
{
DeleteCommand = new RelayCommand
(()= > DeleteSelectedItemListBox(),
()= > isSelected);
}

private bool isSelected;

private string selectedItem;
public string SelectedItem
{
get { return selectedItem; }
set
{
Set( ref selectedItem,值跨度>); // **见下文
isSelected =!string.IsNullOrEmpty(SelectedItem);
}
}



** ViewModel需要继承Galasoft ViewModelBase



现在要删除该项目,您只需要在以下位置添加以下内容,即从中删除 SelectedItem 集合:

  if (!string.IsNullOrEmpty(SelectedItem))
{
ListBox.Remove(SelectedItem);
SelectedItem = string .Empty;
}



最后,为了防止任何混淆,请不要调用集合 ListBox 而是有意义的如 ContactNames SelectedItem as SelectedContact 。现在,您的代码通过以下两个简单的更改进行自我描述:

 ContactNames.Remove(SelectedContact); 



另外,你正在使用 RelayCommand 的错误命名空间。更改:

 使用 GalaSoft.MvvmLight.Command; 



to:

 使用 GalaSoft.MvvmLight.CommandWpf; 



所以你的 MainWindowViewModel 现在看起来像:

 使用 GalaSoft.MvvmLight; 
使用 GalaSoft.MvvmLight.CommandWpf;
使用 PhoneBook.View;
使用 System.Collections.Generic;
使用 System.Data;
使用 System.IO;
使用 System.Linq;

namespace PhoneBook.ViewModel
{
class MainWindowViewModel:ViewModelBase
{
#region构造函数

public MainWindowViewModel()
{
InitializeRelayCommands();
ReadTextFile();
}

#endregion

#region属性

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

private bool isSelected;

private string selectedContact;
public string SelectedContact
{
get { return selectedContact; }
set
{
Set( ref selectedContact,值跨度>);
isSelected =!string.IsNullOrEmpty(selectedContact);
}
}
#endregion

#region方法

私有 void PopUpWindSelectedContact()
{

}

private void DeleteSelectedContactContactNames()
{
string FileName =( @ C:\ Users \StanleyM\Desktop\PhoneBook \ PhoneBook \bin\Debug\Personal.text);
StreamReader streamReader = new StreamReader(FileName);
string line = ;
int Counter = -1;

while ((line = streamReader.ReadLine())!= null
{
foreach var item in 行)
{
if (item == SelectedContact)
{
Counter- - ;
ContactNames.Remove(line);
}
}
}
}

public void ReadTextFile()
{
string FileName =( @ C:\ Users \StanleyM \Desktop\PhoneBook \ PhoneBook \bin\Debug\Personal.text);
DataTable dt = new DataTable( Client 跨度>);
StreamReader streamReader = new StreamReader(FileName);
string line = ;
int 计数器= 0 ;
while ((line = streamReader.ReadLine())!= null
{
Counter ++;
ContactNames.Add(item:line);
}
}

私人 void PopUpWindow( )
{
AddEditView PopUp = new AddEditView();
PopUp.ShowDialog();
}

#endregion

#region RelayCommand

public RelayCommand AddCommand { get ; private set ; }
public RelayCommand DeleteCommand { get ; private set ; }

private void InitializeRelayCommands()
{
AddCommand = new RelayCommand
(()= > PopUpWindow());

DeleteCommand = new RelayCommand
(()= > DeleteSelectedContactContactNames(),
()= > isSelected);
}

#endregion
}
}


I have a PhoneBook App which adds and save users input in a textfile I am trying to have a function which enable the user to be able to select users details from a Listbox then delete them. As well when you click on the users a screen must popup with the users details and enable you to edit and save again to textfile.
I have tried the DeletedSelectedItemListBox which I have created below in order to be able to delete selected Item from my Listbox.

What I have tried:

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using PhoneBook.View;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;

namespace PhoneBook.ViewModel
{
    class MainWindowViewModel : ViewModelBase
    {
        #region Constructor
        public MainWindowViewModel()
        {
            ReadTextFile();
        }

        #endregion
        #region Properties
        public const string MyListPropertyName = "ListBox";
        private List<string> _listBox = null;
        public List<string> ListBox
        {
            get
            {
                return _listBox = _listBox ?? new List<string>();
            }
            set
            {
                if (_listBox == value)
                {
                    return;
                }
                RaisePropertyChanged(MyListPropertyName);
                _listBox = value;
                RaisePropertyChanged(MyListPropertyName);
            }
          
          
        }
        private string _selectedItem = null;
        public string SelectedItem
        {
            get
            {
                return _selectedItem;
            }
            set
            {
                if (_selectedItem != null)
                {
                    return;
                }
                _selectedItem = value;
                RaisePropertyChanged();
            }
        }



        #endregion

        #region Method

        private void PopUpWindSelectedItem()
        {
           
        }

        private void DeleteSelectedItemListBox()
        {
            string FileName = (@"C: \Users\StanleyM\Desktop\PhoneBook\PhoneBook\bin\Debug\Personal.text");
            StreamReader streamReader = new StreamReader(FileName);
            string line = "";
            int Counter = -1;
            
            while ((line = streamReader.ReadLine()) != null)
            {
                foreach (var item in line)
                {
                    if (item.ToString() == SelectedItem.ToString())
                    {
                        Counter--;
                        ListBox.Remove(line);
                    }
                    
                }
               
            }

        }

        public void ReadTextFile()
        {
            string FileName = (@"C: \Users\StanleyM\Desktop\PhoneBook\PhoneBook\bin\Debug\Personal.text");
            DataTable dt = new DataTable("Client");
            StreamReader streamReader = new StreamReader(FileName);
            string line = "";
            int Counter = 0;
            while ((line = streamReader.ReadLine()) != null)
            {
                Counter++;
                ListBox.Add(item: line);
            }
        }

        private void PopUpWindow()
        {
            AddEditView PopUp = new AddEditView();
            PopUp.ShowDialog();

        }


        #endregion
        #region RelayCommand

        private RelayCommand _addCommand = null;
        public RelayCommand AddCommand
        {
            get
            {
                return _addCommand = _addCommand ?? new RelayCommand(() => PopUpWindow());
            }
        }

        private RelayCommand _deleteCommand = null;
        public RelayCommand DeleteCommand
        {
            get
            {
                return _deleteCommand = _deleteCommand ?? new RelayCommand(() => DeleteSelectedItemListBox());
            }
        }


        #endregion
    }
}

First thing, You need to use a Collection type That will notify the UI of any changes. So this:
public const string MyListPropertyName = "ListBox";
private List<string> _listBox = null;
public List<string> ListBox
{
	get
	{
		return _listBox = _listBox ?? new List<string>();
	}
	set
	{
		if (_listBox == value)
		{
			return;
		}
		RaisePropertyChanged(MyListPropertyName);
		_listBox = value;
		RaisePropertyChanged(MyListPropertyName);
	}
}


can be changed to this:

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


Your XAML is missing so I can't see if the SelectedItem property is bound correctly.

I also can not check if your DeleteCommand is enabled correctly. The RelayCommand supports enabling and disabling the bound button. So you could wire it up like:

public RelayCommand DeleteCommand { get; private set; }

private void InitializeRelayCommands()
{
    DeleteCommand  = new RelayCommand
                    (() => DeleteSelectedItemListBox(),
                     () => isSelected);
}

private bool isSelected;

private string selectedItem;
public string SelectedItem
{
    get { return selectedItem; }
    set
    {
        Set(ref selectedItem, value); // ** see below
        isSelected = !string.IsNullOrEmpty(SelectedItem);
    }
}


** The ViewModel needs to inherit the Galasoft ViewModelBase.

Now to delete the item, you only need to add the following where you want to remove the SelectedItem from the collection:

if (!string.IsNullOrEmpty(SelectedItem))
{
    ListBox.Remove(SelectedItem);
    SelectedItem = string.Empty;
}


Lastly, to prevent any confusion, don't call the collection ListBox but instead something meaningful like ContactNames and SelectedItem as SelectedContact. Now your code is self-describing with these two simple changes:

ContactNames.Remove(SelectedContact);


Also, you're using the incorrect namespace for the RelayCommand.Change:

using GalaSoft.MvvmLight.Command;


to:

using GalaSoft.MvvmLight.CommandWpf;


So your MainWindowViewModel now looks like:

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using PhoneBook.View;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
 
namespace PhoneBook.ViewModel
{
    class MainWindowViewModel : ViewModelBase
    {
        #region Constructor
        
		public MainWindowViewModel()
        {
			InitializeRelayCommands();
            ReadTextFile();
        }
 
        #endregion
		
        #region Properties
        
        public ObservableCollection<string> ContactNames { get; set; }
            = new ObservableCollection<string>(); 

		private bool isSelected;
		 
		private string selectedContact;
		public string SelectedContact
		{
			get { return selectedContact; }
			set
			{
				Set(ref selectedContact, value);
				isSelected = !string.IsNullOrEmpty(selectedContact);
			}
		}
        #endregion
 
        #region Method
 
        private void PopUpWindSelectedContact()
        {
           
        }
 
        private void DeleteSelectedContactContactNames()
        {
            string FileName = (@"C: \Users\StanleyM\Desktop\PhoneBook\PhoneBook\bin\Debug\Personal.text");
            StreamReader streamReader = new StreamReader(FileName);
            string line = "";
            int Counter = -1;
            
            while ((line = streamReader.ReadLine()) != null)
            {
                foreach (var item in line)
                {
                    if (item == SelectedContact)
                    {
                        Counter--;
                        ContactNames.Remove(line);
                    }
                }
            }
        }
 
        public void ReadTextFile()
        {
            string FileName = (@"C: \Users\StanleyM\Desktop\PhoneBook\PhoneBook\bin\Debug\Personal.text");
            DataTable dt = new DataTable("Client");
            StreamReader streamReader = new StreamReader(FileName);
            string line = "";
            int Counter = 0;
            while ((line = streamReader.ReadLine()) != null)
            {
                Counter++;
                ContactNames.Add(item: line);
            }
        }
 
        private void PopUpWindow()
        {
            AddEditView PopUp = new AddEditView();
            PopUp.ShowDialog();
        }

        #endregion

        #region RelayCommand
 
        public RelayCommand AddCommand { get; private set; }
		public RelayCommand DeleteCommand { get; private set; }
		 
		private void InitializeRelayCommands()
		{
			AddCommand = new RelayCommand
			                (() => PopUpWindow());

			DeleteCommand  = new RelayCommand
							(() => DeleteSelectedContactContactNames(),
							 () => isSelected);
		}

        #endregion
    }
}