He pasado muchas horas con este problema.Vinculación colección observable a ListBox en XAML
tengo una clase con los datos:
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);
}
}
siguiente que tiene una clase con ObservableCollection de clase userClass:
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();
}
}
De hecho, después de mucho probar una edición, gran parte del código no funciona, como la serialización. Pero no es necesario para el enlace de datos y vinculante es lo que estoy resolviendo ahora.
Tengo esta colección y quiero vincularla a listBox. He intentado de varias maneras, pero no lo he hecho funcionar.
La última vez que lo intenté me dio el error de escritura:
The resource 'users' cannot be resolved.
<ListBox Grid.Column="0" Name="userViewLeft" ItemsSource="{Binding Source={StaticResource users} }" />
como un primer disparo, que iba a tratar de hacer la clase y sus propiedades públicas – thumbmunkeys
En una nota personal, yo pido que no sufijo todos sus nombres de las clases con 'clase' –