我花了很多时间处理这个问题。将可观察的集合绑定到XAML中的ListBox
我有一个数据类:
class userClass : INotifyPropertyChanged
{
public int _key;
private string _fullName;
private string _nick;
public int key
{
get{return _key;}
set { _key = value; NotifyPropertyChanged("key"); }
}
private string nick
{
get { return _nick; }
set { _nick = value; NotifyPropertyChanged("nick"); }
}
private string fullName
{
get { return _fullName; }
set { _fullName = value; NotifyPropertyChanged("fullName"); }
}
public userClass()
{
nick = "nickname";
fullName = "fullname";
}
public userClass(String nick, String name, int key)
{
this.nick = nick;
this.fullName = name;
}
//INotifzPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public override string ToString()
{
return string.Format("{0} {1}, {2}", key, nick, fullName);
}
}
接下来我有一类UserClass的类的ObservableCollection:
class userListClass : ObservableCollection<userClass>
{
public userListClass(){}
//public override void Add(userClass user)
//{
// //user.PropertyChanged += new PropertyChangedEventHandler(user);
// base.Add(user);
//}
~userListClass()
{
//Serialize();
}
public void Serialize(ObservableCollection<userClass> usersColl)
{
FileStream fs = new FileStream("DataFile.dat", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, usersColl);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
}
public void Deserialize()
{
FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
try
{
BinaryFormatter formatter = new BinaryFormatter();
//users = (Hashtable) formatter.Deserialize(fs);
//usersColl = (ObservableCollection<userClass>)formatter.Deserialize(fs);
}
catch (SerializationException e)
{
MessageBox.Show(" Error: " + e.Message);
throw;
}
finally
{
fs.Close();
}
}
public override string ToString()
{
return "test";
//return base.ToString();
}
}
事实上,经过大量的测试编辑,代码很大一部分的不起作用,比如序列化。但是,数据绑定和绑定不是必须的,现在我正在解决这个问题。
所以我有这个集合,并希望将它绑定到listBox。 我尝试了几种方法,但没有得到它的工作。
最后一个我想给我的写错误:
The resource 'users' cannot be resolved.
<ListBox Grid.Column="0" Name="userViewLeft" ItemsSource="{Binding Source={StaticResource users} }" />
作为第一炮,我会尽量让类和它的公共 – thumbmunkeys
性质就我个人而言,我求你不要用“类后缀所有的类名 –