XAML and WPF - Passing Variables to XAML Windows

前端 未结 4 1081
难免孤独
难免孤独 2021-01-01 01:22

I\'m pretty new to WPF and i\'m trying to load a XAML window and pass a variable to this XAML in its constructor or so, because i need it to load some items from this passed

4条回答
  •  再見小時候
    2021-01-01 02:02

    Try to use MVVM (Model-View-ViewModel) pattern.

    You need Model:

    class Person
    {
        public string Name { get; set; }
    }
    

    View is your window or UserControl.

    ViewModel can be something like that:

    class PersonViewModel : INotifyPropertyChanged
    {
     private Person Model;
     public ViewModel(Person model)
     {
      this.Model = model;
     }
    
     public string Name
     {
      get { return Model.Name; }
      set
      {
       Model.Name = value;
       OnPropertyChanged("Name");
      }
     }
    
     public event PropertyChangedEventHandler PropertyChanged;
     private void OnPropertyChanged(string propertyName)
     {
      var e = new PropertyChangedEventArgs(propertyName);
      PropertyChangedEventHandler changed = PropertyChanged;
      if (changed != null) changed(this, e);
     }
    }
    

    Then you need to specify DataContext for your window:

    View.DataContext = new PersonViewModel(somePerson);
    

    And then define bindings in XAML:

    
    
        
        
    
    

    MVVM makes code very elegant and easy.

    You can also try PRISM or Caliburn (http://caliburn.codeplex.com/) frameworks but they are more complex.

提交回复
热议问题