收录日期:2021/01/26 16:10:56 时间:2015-04-14 21:34:15 标签:c#,wpf,xaml

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 variable.

Could anyone point me to the direction of how to go about this please? How does one start up a XAML window and give it a variable please?

Thanks in advance.. Erika

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:

<UserControl x:Class="SomeApp.View"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300">
<Grid>
    <TextBlock Text="{Binding Name}" />
<Grid>    
<UserControl>

MVVM makes code very elegant and easy.

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

Typically, in WPF, you'd create the items you want to load, and set the Window (or UserControl)'s DataContext to the class that contains your items. You can then bind directly to these in order to do custom display from the XAML.

My issue was that i wanted to access a class outside of the XAML window, not communicate with the relative code via Binding. For this, all i needed to do was create a static class to hold the value i required. Simple, yet the solution escaped me at that point. Its a rather dirty way to go round solving the problem but it does the trick.

I would like to thank both contributors who helped me understand the MVVM architecture as I hadnt really understood that previously.

Thanks so much for the prompt reply and sorry if my question was easily missunderstood! Sometimes im not very good at conveying my ideas..

If you want to see a bit more on MVVM then check out this (MVVM is really powerful and a great way to develop testable code):

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

It should give you a very good idea of MVVM. There is an example you can download just under the heading where it says: Code download available from the MSDN Code Gallery.