2012-09-07 43 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

相關問題