2012-09-07 41 views
1

有一个简单的XAML用户控件,我想将DataContext设置为(xaml.cs)文件后面的代码。WPF用户控件的datacontext代码隐藏属性

我想设置的DataContext和ItemsSource时在XAML,这样我就可以与物业ListOfCars填充组合框

XAML

<UserControl x:Class="Sample.Controls.MyControl" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="85" d:DesignWidth="200"> 
    <Grid Height="85" Width="200" Background="{StaticResource MainContentBackgroundBrush}"> 
     <StackPanel Orientation="Vertical">     
      <ComboBox Height="23.338" x:Name="CarList" />     
     </StackPanel>  
    </Grid> 
</UserControl> 

代码背后

public List<Cars> ListOfCars 
{ 
    get { return _store.ListCars(); } 
} 

换句话说,而不是在代码隐藏中这样做,我如何设置绑定在XAML中

public MyControl() 
{ 
    InitializeComponent(); 
    _store = new Store(); 
    CarList.ItemsSource = _store.ListCars(); 
    CarList.DisplayMemberPath = "Name"; 
} 

回答

1

只要绑定ItemsSource即可。

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

然后为用户控件:

<MyControl DataContext="{Binding *viewModel*}"/> 

你要绑定您的用户控件使用,而不是在定义的DataContext,因为在定义你不知道要什么给绑定。 Combobox自动处于控件的上下文中,因此您可以将其绑定到DataContext而无需任何其他工作。

结合到资源实例:

<Application.Resources> 
    ... 
    <viewmodels:ViewModelLocator x:Key="ViewModelLocator"/> 
    ... 
</Application.Resources> 


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

此创建ViewModelLocator的一个实例,然后结合控制该资源的DataContext的。

+0

不太理解{Binding viewModel}。这不起作用,但viewModel如何绑定到背后的代码,而不是在某种程度上挂钩它。没有针对此xaml的特定视图模型 – Kman

+0

您必须在某处定义您的视图模型。这可以是你使用你的控件的'DataContext'(然后像这样绑定'{Binding}'),或者它可以是一个静态资源(然后像这样绑定'{Binding Source = {StaticResource * resource name *}} ,但你必须定义你要绑定到什么地方 – mydogisbox

+0

通读以下关于绑定到视图模型的一些基础知识:http://msdn.microsoft.com/en-us/library/hh821028.aspx – mydogisbox

1

Do not do that,你会搞乱DataContext的所有外部绑定。改为使用UserControl.NameElementName绑定(或RelativeSource)。

+0

我不认为这就是他打算做的。这似乎更像是他对如何设置绑定感到困惑。 – mydogisbox

相关问题