2011-10-07 14 views
7

'daki ListBox'a bağlanması, bu sorunla çok fazla saat harcadım.Gözlemlenebilir koleksiyonun XAML

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); 
    } 

} 

Ardından KullanıcıSınıfı sınıfının ObservableCollection bir sınıf olması:

I verilerle bir sınıf olması

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(); 
    }  
} 

Aslında, kod, büyük bir kısmı, bir düzenleme test çok sonra seri hale getirme gibi çalışmıyor. Ama veri bağlama ve bağlama için gerekli olan şey şu anda çözdüğüm şey değil.

Bu koleksiyona sahibim ve listBox'a bağlamak istiyorum. Birkaç yolu denedim, ancak işe yaramadı.

The resource 'users' cannot be resolved.

Sen 2 şey yapmanız gereken
<ListBox Grid.Column="0" Name="userViewLeft" ItemsSource="{Binding Source={StaticResource users} }" /> 
+3

i sınıfını yapmaya çalışacaktı ve kişisel bir not – thumbmunkeys

+6

kamu özelliklerini, ben size 'Sınıf' ile sınıf isimleri tüm soneki için yalvarıyorum –

cevap

26

Bazı noktalar

  • public değil private.
  • Değişkenler private olun Özellikleri olun

    belirtmek için.
  • Adlandırma Kuralları'nı takip edin ve sınıfın arkasına class eklemeyin.
  • ItemsSource kaynağı, verilerin kapsamı dahilinde olmalıdır. Örneğimde, sınıf kapsamındaki kullanıcı listesi ve Window Loaded olayında ItemSource'u sağladık.

İşte tam bir örnek kod, Grid Kontrolünü ListBox'un içine yerleştirdim, çünkü daha sonra VirtualBoxStackPanel için ListBox özelliğini değiştirebilirsiniz. Böylece listede büyük güncellemeler olduğunda büyük bir performans artışı sağlar. Ayrıca, ObservableCollection performans bilgisinden daha iyi olan BindingList'u kullanabilirsiniz.

Kullanıcı sınıfı:

public class User : INotifyPropertyChanged 
    { 
     private int _key; 
     private string _fullName; 
     private string _nick; 

     public int Key 
     { 
      get { return _key; } 
      set { _key = value; NotifyPropertyChanged("Key"); } 
     } 
     public string NickName 
     { 
      get { return _nick; } 
      set { _nick = value; NotifyPropertyChanged("NickName"); } 
     } 
     public string Name 
     { 
      get { return _fullName; } 
      set { _fullName = value; NotifyPropertyChanged("Name"); } 
     } 

     public User(String nick, String name, int key) 
     { 
      this.NickName = nick; 
      this.Name = name; 
      this.Key = key; 
     } 

     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, NickName, Name); 
     } 
    } 

Kullanıcı Listesi sınıfı:

public class Users : ObservableCollection<User> 
    { 
     public Users() 
     { 
      Add(new User("Jamy", "James Smith", Count)); 
      Add(new User("Mairy", "Mary Hayes", Count)); 
      Add(new User("Dairy", "Dary Wills", Count)); 
     } 
    } 

XAML:

<Grid> 
     <Button Content="Start" Height="23" HorizontalAlignment="Left" Margin="416,12,0,0" x:Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" /> 
     <ListBox x:Name="UserList" HorizontalContentAlignment="Stretch" Margin="12,41,12,12"> 
      <ListBox.ItemTemplate> 
       <DataTemplate> 
         <Grid Margin="10"> 
          <Grid.ColumnDefinitions> 
           <ColumnDefinition Width="20" /> 
           <ColumnDefinition Width="150" /> 
           <ColumnDefinition Width="*" /> 
          </Grid.ColumnDefinitions> 
          <TextBlock Text="{Binding Key}" Margin="3" Grid.Column="0" /> 
          <TextBlock Text="{Binding NickName}" Margin="3" Grid.Column="1" /> 
          <TextBlock Text="{Binding Name}" Margin="3" Grid.Column="2" /> 
         </Grid> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox> 
    </Grid> 

XAML Kod arkasında: İlk atış olarak

public partial class MainWindow : Window 
{ 
    public static Users userslist = new Users(); 
    DispatcherTimer timer = new DispatcherTimer(); 

    public MainWindow() 
    { 
     InitializeComponent(); 
     this.Loaded += new RoutedEventHandler(MainWindow_Loaded); 
    } 

    void MainWindow_Loaded(object sender, RoutedEventArgs e) 
    { 
     timer.Interval = DateTime.Now.AddSeconds(10) - DateTime.Now; 
     timer.Tick += new EventHandler(timer_Tick); 
     UserList.ItemsSource = userslist; 
    } 

    void timer_Tick(object sender, EventArgs e) 
    { 
     userslist.Add(new User("Jamy - " + userslist.Count, "James Smith", userslist.Count)); 
     userslist.Add(new User("Mairy - " + userslist.Count, "Mary Hayes", userslist.Count)); 
     userslist.Add(new User("Dairy - " + userslist.Count, "Dary Wills", userslist.Count)); 
    } 

    private void button1_Click(object sender, RoutedEventArgs e) 
    { 
     if (button1.Content.ToString() == "Start") 
     { 
      button1.Content = "Stop"; 
      timer.Start(); 
     } 
     else 
     { 
      button1.Content = "Start"; 
      timer.Stop(); 
     } 
    } 

} 
+2

Çok teşekkür ederim. "UserList.ItemsSource = userslist;" ve XAML kodu bana çok yardımcı oldu. – prespic

+1

Bunun çok uzun zaman önce olduğunu biliyorum, ama bu bana çok yardımcı oldu. Böyle kısa bir cevap. Şu anda 'ListBox' kendisi bağlaca referans olarak yüklendiğinde bir hata alıyorum, ancak kodunuzun yardımıyla birçok hatayla çalıştım. Kudos! – plast1K

2

:

denedim sonuncusu bana yazma hata verdi Öncelikle

ne olursa olsun elemanı (Window/UserControl/içinde DataContext set olursa olsun) aşağıdaki gibi görünen bir nesneye ListBox kodunu içerir:

public class ViewModel 
{ 
    public ViewModel() { this.users = new userListClass(); } 
    public userListClass users { get; private set; } 
} 

Bu sizin görünüm modelinizdir ve bağlamak istediğiniz şey budur.

İkinci olarak, bağlamanızı ItemsSource="{Binding Path=users}" olarak değiştirin. DataContext ebeveynden gelen Çünkü bu. this.DataContext üzerinde mülkiyet users değerine benim ItemsSource özelliğinin değerini ayarlamak" çevirir ve, senin ListBox artık kullanıcı listesini görüntüler yukarıdaki ViewModel sınıfına bu ayarlayın.