2016-05-05 5 views
-1

Я совершенно новый для WPF, и у меня проблемы с обновлениями ItemsSource. Я создал одно основное приложение Metro с вкладками (TabItem (s) как UserControlDataContext="{Binding}"), в котором отображаются разные данные/разные методы.Как правильно обновить UserControl с помощью Itemource?

То, с чем я столкнулся, - это INotifyPropertyChanged (я не смог понять решение моей проблемы из похожих примеров/вопросов). Я пытаюсь сделать это, если новые данные вводятся в окне (которое инициализируется из одного из UserControl), ComboBox в другом UserControl (или TabItem) будет автоматически обновляться. Вот что у меня есть:

UserControl1.xaml

public partial class UserControl1: UserControl 
{ 
    private userlist addlist; 
    public UserControl1() 
    { 
     InitializeComponent(); 
     fillcombo(); 
    } 
     public void fillcombo() 
    { 
     Fillfromdb F = new Fillfromdb(); // class that simply connects 
     // to a database sets a datatable as ListCollectionView 
     addlist = new addlist { List = F.returnlistview() }; // returns ListCollectionView 
     UsersCombo.ItemsSource = addlist.List; 
    } 

userlist.cs

public class userlist: INotifyPropertyChanged 
    { 
    private ListCollectionView _list; 
    public ListCollectionView List 
    { 
     get { return this._list; } 
     set 
     { 
      if (this._list!= value) 
      { 
       this._list= value; 
       this.NotifyPropertyChanged("List"); 
      } 
     } 
    } 
    public event PropertyChangedEventHandler PropertyChanged; 

    public void NotifyPropertyChanged(string propertyName) 
    { 
     if (this.PropertyChanged != null) 
      this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 
    } 

Registration.xaml (вызывается из другого UserControl)

public partial class Registration: MetroWindow 
{ 
    public Registration() 
    { 
     InitializeComponent(); 
    } 
    private void confirm_button_click(object sender, RoutedEventArgs e) 
    { 
     // new user is saved to database 
     // * here is where I don't know what to do, how to update the ItemSource 

    } 
    } 

Вот установка по ComboBox «s в UserControl.xaml:

<ComboBox x:Name="UsersCombo" 
ItemsSource="{Binding List, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"/> 

Поскольку я не имею никакого программирования образование/опыт очень общие рекомендации/объяснение было бы очень признателен.

EDIT: Registration.xaml с PropertyChanged (до сих пор не работает):

public partial class Registration : MetroWindow 
{ 
    public userlist instance = new userlist(); 
    public ListCollectionView _list1; 
    public ListCollectionView List1 
    { 
     get { return this._list1; } 
     set 
     { 
      if (this._list1 != value) 
      { 
       this._list1 = value; 
       this.NotifyPropertyChanged("List1"); 
      } 
     } 
    } 
    public event PropertyChangedEventHandler PropertyChanged; 

    public void NotifyPropertyChanged(string propertyName) 
    { 
     if (this.PropertyChanged != null) 
      this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 


    public Registration() 
    { 
     InitializeComponent(); 
     instance.List.PropertyChanged += ComboPropertyChangedHandler(); 
    } 
    private void confirm_button_click(object sender, RoutedEventArgs e) 
    { 
     // new user is save to database 
     // still don't now what to do with new ListCollectionView from database 
    } 
    public void ComboPropertyChangedHandler(object obj) 
    { 
     List1 = instance.List; // when new data from database should be loaded? 
    } 

ответ

0

Это где PropertyChanged событие удобна. Привяжите поле со списком на второй странице xaml к списку и создайте аналогичное свойство, как в первом xaml.

Во второй xaml.cs

public partial class Registration: MetroWindow, INotifyPropertyChanged 
{ 
    private userlist instance = new userlist(); 
    private ListCollectionView _list1; 
    public ListCollectionView List1 
    { 
     get { return this._list1; } 
     set 
    { 
     if (this._list1 != value) 
     { 
      this._list1 = value; 
      this.NotifyPropertyChanged("List1"); 
     } 
    } 
} 
public Registration() 
{ 
    InitializeComponent(); 
    instance.List.PropertyChanged += ComboPropertyChangedHandler(); 
} 

private void ComboPropertyChangedHandler(object obj) 
{ 
    List1 = instance.List; 
    //or iterate through the list and add as below 
    foreach(var item in instance.List) 
    { 
     List1.Add(item); 
    } 
} 
private void confirm_button_click(object sender, RoutedEventArgs e) 
    { 
     // new user is saved to database 
     // * here is where I don't know what to do, how to update the ItemSource 
    } 
} 
+0

почему-то говорит, что 'CollectionView.PropertyChanged' недоступен дуэту это уровень защиты, и нет ни одного аргумента для' + = ComboPropertyChangedHandler() ' –

+0

Обеспечить класс и участник - ** публичный ** – ViVi

+0

я сделал это. но он говорит то же самое :( –