简体   繁体   中英

How to bind to a property of a class instantiated in the current class

I have two clasess, MainWindow and MainWindow_ViewModel .

MainWindow is defined like so:

public partial class MainWindow : Window
{
    static public MainWindow wn;
    public MainWindow_ViewModel mwvm;

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

MainWindow_ViewModel is defined like this:

class MainWindow_ViewModel
{
    private List<String> _filtros;
    public List<String> filtros
    {
        get
        {
            return _filtros;
        }
    }


    public MainWindow_ViewModel()
    {
        _filtros = new List<String>();
        _filtros.add("Filtro1");
        _filtros.add("Filtro2");
        _filtros.add("Filtro3");
    }
}

Notice that there is no static methods or properties whatsoever.

In MainWindow's XAML I have a ListBox that I want to bind with the mwvm.filtros which should be available directly from code-behind.

  1. How can I achieve that WITHOUT using DataContext and only in XAML?
  2. Could it be possible to bind from another class (ie another window) to the following path? MainWindow.wn.mwvm.filtros .

Yes, of course. You don't need C# code to bind the view model. Just create an object in the DataContext element:

<Window.DataContext>
   <local:MainWindow_ViewModel />
</Window.DataContext>

You have to create a namespace for your local project though. Full code:

<Window x:Class="Your.Namespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:Your.Namespace"
>
    <Window.DataContext>
        <local:MainWindow_ViewModel />
    </Window.DataContext>

You can't bind from another Window or Control unless you pass it along or make it static. If it is sub control of this Window , you can set its data context.

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