简体   繁体   中英

How to bind to a property of an instantiated class in XAML

I was wondering if it is possible to make a reference to an instance made in code behind of a class, with XAML.

For example: I have two clasess, MainWindow and MainWindow_ViewModel .

MainWindow is defined like so:

public partial class MainWindow : Window
{
    static public MainWindow wn;
    private MainWindow_ViewModel _mwvm;
    public MainWindow_ViewModel mwvm
    {
        get
        {
            return _mwnm;
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        wn = this;
        _mwvm = new MainWindow_ViewModel();
    }
}

1) How could I, in MainWindow.xaml, make a reference to the property MainWindow.wn.mwvm without creating a new instance of MainWindow_ViewModel (the purpose to this is to do some binding without using DataContext but I need to use the same instance of MainWindow_ViewModel throughout the whole application)

2) Is it possible to make a reference to that same property ( MainWindow.wn.mwvm ), from a XAML other than MainWindow.xaml ?

Thanks again for all the support.

First of you should set the DataContext of your window to your ViewModel. Only that way will it's properties be visible in the MainWindow's XAML.

Example:

<Window DataContext="{Binding mwvm}">
    <TextBlock Text="{Binding PathToYourPropertyInVM} />
</Window>

Allways make sure your viewmodels either implement INotifyPropertyChanged or use DependencyProperties for Bindable properties. That is required in order for the UI to "listen" to the changes in the properties values.

If you want a Globally accessible ViewModel, you should look into the ServiceLocator pattern. All of the MVVM framework implement it for you (MVVMLight, Caliburn, etc). It basically consist of a class where your register your components and it handles all the instatiation when it's required. You should do a little research about that topic because it's rather extensive and hard to put on a single answer.

Hope this helps ;)

To instantiate your class in the app.xaml :

  1. Add the namespace in the app.xaml

xmlns:myApp="clr-namespace:WpfApplication1"

  1. Create the object of your class

<myApp:MainWindow_ViewModel x:Key="mwvm" />

An example of use :

<TextBlock Text="{Binding Source={StaticResource mvvm}, Path=A_PROPERTY}"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM