Add object to ObservableCollection List object - c#

How to add one object to ObservableCollection list object? I have class called "Assest" and I have created ObservableCollection list of Asset and I want to maintain it like adding and deleting element from that ObservableCollection list. Now I'm getting error when I try to add single element to ObservableCollection.
Here's my code.
private static ObservableCollection<Assest> _collection = null;
public ObservableCollection<Assest> AssestList
{
get
{
if (_collection == null)
{
_collection = new ObservableCollection<Assest>();
}
return _collection;
}
set { _collection = value; }
}
public static ObservableCollection<Assest> ToObservableCollection(List<Assest> assestList)
{
return new ObservableCollection<Assest>(assestList);
}
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
LoadData();
comboBox1.ItemsSource = AssestList;
}
private void LoadData()
{
Assest assest = new Assest() { AppID = "1", AssestName = "AppName", AppDescription = "Description" };
Assest assest2 = new Assest { AppDescription = "Des2", AppID = "2", AssestName = "hi" };
List<Assest> assList = new List<Assest> {assest, assest2};
ObservableCollection<Assest> generatedAssestList = ToObservableCollection(assList);
AssestList = generatedAssestList;
}
// Here I get an error.
public static void AddAppToObservalCollection(Assest ass)
{
_collection.Add(ass);
}
So How to over come these kind of situations. Thanks everyone.

Your code is a bit messy, it's not clear why you need both AssestList and _collection.
However, I think you need to replace
_collection.Add(ass);
with
AssestList.Add(ass);

_collection object still null while you call the getter of AssestList. So, when you use "_collection.Add(ass);", it can be null (and, btw _collection is private, so you can't access it from static function)
To avoid this, use always AssestList.

Related

I can't use method Filter on ObservableCollection

On my viewModel I developed this code that will allow me to implement a research filter:
public ICollection<Nc> Ncs
{
get
{
var ncs = _ncManager.Ncs;
_ncCollectionView = CollectionViewSource.GetDefaultView(ncs);
_ncCollectionView.Filter = _DoesNcMatchFileNameFilter;
return ncs;
}
}
private ICollectionView _ncCollectionView;
This method works, but if I try to implement another similar method in another viewModel:
private ObservableCollection<Material> _materials;
public ObservableCollection<Material> materials
{
get
{
var materials = Material.Name;
_materialCollectionView = (CollectionViewSource)CollectionViewSource.GetDefaultView(materials);
_materialCollectionView.Filter = _DoesMaterialMatchFileNameFilter;
return Materials;
}
}
private CollectionViewSource _materialCollectionView;
I get an error: CollectionViewSrouce.Filter can only appear on the left hand side of += or -=".
Why can't I do the same thing? What did I do wrong?
I've tried to read this page ObservableCollection<> vs. List<> but it didn't help me.
should _materialCollectionView not be of type ICollectionView?
So:
private ObservableCollection<Material> _materials;
public ObservableCollection<Material> materials
{
get
{
var materials = Material.Name;
_materialCollectionView = CollectionViewSource.GetDefaultView(materials);
_materialCollectionView.Filter = _DoesMaterialMatchFileNameFilter;
return Materials;
}
}
private ICollectionView _materialCollectionView;

How can I iterate through a list with multiple objects from class

I am coding an application for my study, but i'm stuck at this point. I made a class called 'Neighborhood'. This class has a string and an int. In my main code I give the class a value and put it in a list. I now want to loop through my list and get the int out of it (put it in a listbox, or do a calculation). How do I get the int out of the list?
class Wijk
{
private string wijken;
private int tijd;
public string Wijken
{
get { return wijken; }
set { wijken = value; }
}
public int Tijd
{
get { return tijd; }
set { tijd = value; }
}
}
Created the list and the instance of the class.
List<object> Uden = new List<object>();
Wijk Wijkeninput = new Wijk();
Now I value the string and int with a combobox and textbox.
private void wijkAanmaken()
{
Wijkeninput.Wijken = Convert.ToString(cbWijken);
Wijkeninput.Tijd = Convert.ToInt16(tbSnelheid.Text);
Uden.Add(Wijkeninput);
}
For this, instead of having an object list, you can have list containing class objects like
List<Wjik> Uden = new List<Wjik>();
then you can access int as follows:
foreach (Wjik obj in listProgram)
{
int tij = Convert.ToInt32(obj.tijd);
}
First the List can be declared like this:
List<Wijk> Uden = new List<Wijk>();
To iterate over it:
foreach(var item in Uden)
{
var myInt = item.Tijd;
var myString = item.Wijken;
//here do whatever you want with the values
}

Changing the data source of ListView dynamically

I have a ListView and data source for it which it populate from the Internet. Once it's populate it should remain static unless a user makes a new http request. Now I have something like this:
class MyDataItem {
public int Field1 { get; set; }
public string Field2 { get; set; }
}
class Window1: Window {
private List<MyDataItem> dataSource = new ...
void sendHttpRequest(...) {
dataSource = getFromInternet();
myListView.ItemsSource = dataSource ;
}
}
And say, I have a checkbox. When I click on it, I want to filter the data by some filter.
//.........
// the checkbox is checked
var filterDataSource = dataSource.Where(....)
How can I make my ListView update its data with data source to be filterDataSource? And then when the checkbox is unchecked again, how will I make it show the initial data source?
Here is some code to help you. Please note that this was not tested nor compiled but it can give you some hints on how to handle your case. The trick is to use a CollectionViewSource that lets you filter your data.
class Window1: Window {
private readonly ObservableCollection<MyDataItem> _children;
private readonly CollectionViewSource _viewSource;
public Window1()
{
// ...
_children = new ObservableCollection<MyDataItem>();
_viewSource = new CollectionViewSource
{
Source = _children
};
myListView.ItemsSource = _viewSource;
// ...
}
// This method needs to be called when your checkbox state is modified.
// "filter = null" means no filter
public void ApplyFilter(Func<MyDataItem, bool> filter)
{
if (_viewSource.View.CanFilter)
{
_viewSource.View.Filter = (filter == null) ? (o => true): (o => filter((MyDataItem) o));
}
}

Cast IEnumerable to custom ObservableCollection Class?

Is it possible to convert IEnumerable to a Custom Class that is inherting from ObservableCollection class?
Reason is I want to select only a filtered set of items on the get. I want to implement it on the get because lots of other properties reference CustomItems and perform processes on the items, but I want to somehow make it process filtered set of items depending if a value is enabled or not.
Below is code to help explain what I want to achieve:
public class CustomItemsCollection : ObservableCollection<ItemViewModel>
{
public ListView ListView { get; set; }
public void ScrollToItem(object item = null)
{
//Some custom Code
}
}
And here is my property that I want to customize:
private CustomItemsCollection _CustomItems = null;
[JsonProperty]
public CustomItemsCollection CustomItems
{
get
{
if (_CustomItems != null)
{
if(SomeValueIsEnabled)
{
var filteredItems = _CustomItems.Where(c => c.Property.equals(SomeValue));
var castedItems = (CustomItemsCollection)filteredItems;
return castedItems;
}
return _CustomItems;
}
_CustomItems = new CustomItemsCollection();
_CustomItemsChangedSource = new CollectionChangedWeakEventSource();
_CustomItemsChangedSource.SetEventSource(_CustomItems);
_CustomItemsChangedSource.CollectionChanged += _CustomItemsChangedSource_CollectionChanged;
return _CustomItems;
}
set { _CustomItems = value; RaisePropertyChanged("CustomItems"); }
}
Specifically, this part:
if(SomeValueIsEnabled)
{
var filteredItems = _CustomItems.Where(c => c.Property.equals(SomeValue));
var castedItems = (CustomItemsCollection)filteredItems;
return castedItems;
}
Is this possible / or maybe wrong? What is the best practice to do it?
Thank you!
You can't just cast it, but you can create an instance of CustomItemsCollection and initialize it with filteredItems.
Add a constructor to your custom class that passes through to the appropriate ObservableCollection constructor:
public class CustomItemsCollection : ObservableCollection<ItemViewModel>
{
public CustomItemsCollection(IEnumerable<ItemViewModel> items)
: base(items) { }
// your other code here
}
Then you can do this:
var filteredItems = _CustomItems.Where(c => c.Property.equals(SomeValue));
var collection = new CustomItemsCollection(filteredItems);
return collection;
Try with this code:
var filteredItems = _CustomItems.Where(c => c.Property.equals(SomeValue))
.Select(pre=> new ItemViewModel(){
//add info here
});
var castedItems = new CustomItemsCollection(filteredItems);

Setting property inside method [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
Is something like the following possible or do you have to return the list and assign it afterwards? I get object reference not set to instance of an object.
public class MyCollection
{
public List<SomeObject> Collection { get; set; }
public List<SomeObject> CreateCollection()
{
// Is there a way to set the Collection property from here???
this.Collection.Add(new SomeObject()
{
// properties
});
}
}
...
MyCollection collection = new MyCollection();
collection.CreateCollection();
Yes, you can use an object initializer:
public List<SomeObject> CreateCollection()
{
// You may want to initialize this.Collection somehere, ie: here
this.Collection = new List<SomeObject>();
this.Collection.Add(new SomeObject
{
// This allows you to initialize the properties
Collection = this.Collection
});
return this.Collection;
}
Note that this will still potentially have an issue - you are never initializing this.Collection in any code you're displaying. You will need to initialize it to a proper collection in your constructor or via some other mechanism.
It is also an odd choice to have a "Create" method that initializes the local variable and returns a List<T>. Typically, you'd do one or the other. A more common approach would be to place this code within the constructor:
public class MyCollection
{
public IList<SomeObject> Collection { get; private set; } // The setter would typically be private, and can be IList<T>!
public MyCollection()
{
this.Collection = new List<SomeObject>();
this.Collection.Add(new SomeObject
{
Collection = this.Collection
});
}
}
You could then use it via:
MyCollection collection = new MyCollection();
var object = collection.Collection.First(); // Get the first element
That being said, in general, there is no real reason to make a custom class for a collection like this in most cases. Just using a List<SomeObject> directly is typically sufficient.
It's completely possible - you just have to instantiate it first, before you can use it:
public List<SomeObject> CreateCollection()
{
this.Collection = new List<SomeObject>(); // this creates a new list - the default if you just define a list but don't create it is for it to remain null
this.Collection.Add(new SomeObject()
{
// whatever
});
}
Of course, as pointed out in a comment, if you want that function to return a list, it would have to actually return the list. Presumably you mean public void CreateCollection(), though, since that was your question, whether you actually had to return a list (answer: no).
You must initialize this.Collection before adding elements into it.
public List<SomeObject> CreateCollection()
{
this.Collection = new List<SomeObject>();
this.Collection.Add(new SomeObject()
{
// properties
});
}
You can use a list initializer in this case:
public class Person
{
public string Name { get; set; }
public string Firstname { get; set; }
}
class Program
{
public static List<Person> Collection { get; set; }
public static List<Person> CreateCollection()
{
return new List<Person>()
{
new Person() { Name = "Demo", Firstname = "Demo1"},
new Person() { Name = "Demo", Firstname = "Demo1"},
};
}
static void Main(string[] args)
{
Collection = CreateCollection();
}
}

Categories

Resources