[英]How to bind to a property of a class instantiated in the current class
I have two clasess, MainWindow
and MainWindow_ViewModel
. 我有两个分类,
MainWindow
和MainWindow_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
,应该直接从后台代码中使用它们。
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. 除非您将其传递给其他
Window
或Control
,或者将其设置为静态,否则您不能与之绑定。 If it is sub control of this Window
, you can set its data context. 如果它是此
Window
子控件,则可以设置其数据上下文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.