Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
WPF用户控制';将datacontext设置为codebehind中的属性_Wpf - Fatal编程技术网

WPF用户控制';将datacontext设置为codebehind中的属性

WPF用户控制';将datacontext设置为codebehind中的属性,wpf,Wpf,有了一个简单的XAML用户控件,我想将DataContext设置为代码隐藏(XAML.cs)文件 我想在XAML中设置DataContext和Itemssource,以便用属性ListOfCars填充组合框 XAML 只需绑定项资源 <ComboBox ItemsSource="{Binding ListOfCars}"/> 这将创建ViewModelLocator的实例,然后将控件的DataContext绑定到该资源。,您将搞乱到DataContext的所有外部绑定。使用User

有了一个简单的XAML用户控件,我想将DataContext设置为代码隐藏(XAML.cs)文件

我想在XAML中设置DataContext和Itemssource,以便用属性ListOfCars填充组合框

XAML


只需绑定
项资源

<ComboBox ItemsSource="{Binding ListOfCars}"/>

这将创建ViewModelLocator的实例,然后将控件的DataContext绑定到该资源。

,您将搞乱到
DataContext的所有外部绑定。使用
UserControl.Name
ElementName
绑定(或
RelativeSource
)。

不要完全获取{Binding viewModel}。它不起作用,但是viewModel如何绑定到后面的代码,而不以某种方式连接它。没有此XAML的特定视图模型您必须在某处定义视图模型。这可以是使用控件的
DataContext
(然后像这样绑定
{Binding}
),也可以是静态资源(然后像这样绑定
{Binding Source={StaticResource*resource name*})
,但您必须定义要绑定到的内容。通读本文,了解绑定到视图模型的一些基本知识:谢谢,…我知道我应该仔细阅读,因为我目前的绑定知识非常有限:)但我真的没有为此使用MVVM模式。。至少在我看来不是这样。就像在xaml中而不是在代码隐藏中进行绑定一样(请参见问题更新),我不认为他打算这么做。似乎他只是对如何设置装订感到困惑。
public List<Cars> ListOfCars
{
  get { return _store.ListCars(); }
}
public MyControl()
{
  InitializeComponent();
  _store = new Store();
  CarList.ItemsSource = _store.ListCars();
  CarList.DisplayMemberPath = "Name";
}
<ComboBox ItemsSource="{Binding ListOfCars}"/>
<MyControl DataContext="{Binding *viewModel*}"/>
<Application.Resources>
  ...
  <viewmodels:ViewModelLocator x:Key="ViewModelLocator"/>
  ...
</Application.Resources>


<MyControl DataContext="{Binding Source={StaticResource ViewModelLocator}}"/>