How to update Sample Data in C#
I have this sample data. Right now it is defined in a seperate C# file like this:
public class SampleData{
public static ObservableCollection<Product> GetSampleData(){
ObservableCollection<Product> teams = new ObservableCollection<Product>();
}
}
and I load the obsevableCollection
inside GetSampleData()
.
It works and I am able to get the Sample-Data
anywhere in my pro开发者_运维百科gram.
But how can I redesign this code so that I can create the sample data on the fly from outside the class?
What you are trying to implement is called a singleton pattern. It allows you to store a single instance of an object.
Basically your problem is that every time you call GetSampleData
you are creating a new instance of the ObservableCollection<Product>
so you can’t get the same data gain by calling the method again. Your actual sample I think is not what you meant because in it’s posted form it wouldn’t compile because you missed the return teams;
.
I am guessing you want something like this:
public class SampleData
{
private static ObservableCollection<Product> _Instance;
public static ObservableCollection<Product> Instance
{
get
{
// Create a new collection if required.
if (SampleData._Instance == null)
{
// Cache instance in static field.
SampleData._Instance = new ObservableCollection<Product>();
}
// Return new or existing collection.
return SampleData._Instance;
}
}
}
Basically we are creating the object instance on the first call so when you call the Instance
property again you get the same instance.
Use it like this:
// Add the data to the ObservableCollection<Product>.
SampleData.Instance.Add(new dataObjectOrWhatEver());
// Get index 0 from the collection.
var someObject = SampleData.Instance[0];
public class SampleData{
static ObservableCollection<Product> teams = null;
static public ObservableCollection<Product> Teams{
get{
if(teams == null)
teams = GetSampleData();
return teams;
}
set{
teams = value;
}
}
// make this one private
private static ObservableCollection<Product> GetSampleData(){
ObservableCollection<Product> t = new ObservableCollection<Product>();
// fill t with your data
return t;
}
}
AND for the cunsumer:
public class MyCunsumerClass{
// the method that uses the Team that provided by SampleData
public void MyMethod(){
this.flatteningTreeView.ItemsSource = SampleData.Teams;
}
public void MyFillerMethod(){
var my_new_data = new ObservableCollection<Product>(); // or anything else you want to fill the Team with it.
SampleData.Teams = my_new_data;
// SampleData.Teams has new value you suplied!
}
public void MyChangerMethod(){
var t = SampleData.Team;
t.AnyProperty = my_value;
t.OtherProperty = my_value_2;
// SampleData.Team's properties changed!
}
}
精彩评论