简体   繁体   English

如何绑定到在当前类中实例化的类的属性

[英]How to bind to a property of a class instantiated in the current class

I have two clasess, MainWindow and MainWindow_ViewModel . 我有两个分类, MainWindowMainWindow_ViewModel

MainWindow is defined like so: MainWindow的定义如下:

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: MainWindow_ViewModel的定义如下:

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. 在MainWindow的XAML中,我有一个想要与mwvm.filtros绑定的mwvm.filtros ,应该直接从后台代码中使用它们。

  1. How can I achieve that WITHOUT using DataContext and only in XAML? 如何不使用DataContext且仅在XAML中实现该目标?
  2. Could it be possible to bind from another class (ie another window) to the following path? 是否可以从另一个类(即另一个窗口)绑定到以下路径? MainWindow.wn.mwvm.filtros . MainWindow.wn.mwvm.filtros

Yes, of course. 当然是。 You don't need C# code to bind the view model. 您不需要C#代码来绑定视图模型。 Just create an object in the DataContext element: 只需在DataContext元素中创建一个对象:

<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. 除非您将其传递给其他WindowControl ,或者将其设置为静态,否则您不能与之绑定。 If it is sub control of this Window , you can set its data context. 如果它是此Window子控件,则可以设置其数据上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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