2011-08-25 74 views
6

我有這個簡單的應用,增加了一些項目的組合框:設置的DataContext在XAML

public partial class Window1 : Window 
    { 
     private ObservableCollection<string> _dropDownValues = new ObservableCollection<string>(); 
     public ObservableCollection<string> DropDownValues 
     { 
      get { return _dropDownValues; } 
      set { _dropDownValues = value; } 
     } 

     private string _selectedValue; 
     public string SelectedValue 
     { 
      get { return _selectedValue; } 
      set { _selectedValue = value; } 
     } 

     public Window1() 
     { 
      InitializeComponent(); 
      DataContext = this; 

      DropDownValues.Add("item1"); 
      DropDownValues.Add("item1"); 
      DropDownValues.Add("item1"); 
      DropDownValues.Add("item1"); 
      DropDownValues.Add("item1"); 
      DropDownValues.Add("item1"); 
     } 
    } 

這裏是XAML文件:

<Window x:Class="WpfApplication2.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Window1" Height="300" Width="300"> 
    <StackPanel HorizontalAlignment="Left" Margin="10"> 
     <ComboBox 
      Margin="0 0 0 5" 
      ItemsSource="{Binding DropDownValues}" 
      SelectedValue="{Binding SelectedValue}"   
      Width="150"/>  
    </StackPanel> 
</Window> 

能有人告訴我我該怎麼設置來自xaml文件的DataContext,而不是在構造函數中初始化?

謝謝。

回答

23

只要改變WindowDataContext結合自身:

<Window x:Class="WpfApplication2.Window1" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="Window1" Height="300" Width="300" 
     DataContext="{Binding RelativeSource={RelativeSource Self}}" ... /> 
0

我相信這種情況下的DataContext是隱式的,因爲您使用的是後面的代碼,所以不必設置。如果您使用的是MVVM,則可以在該XAML標記內添加對該文件夾和類的引用,並將該資源關鍵字設置爲等於可以在子元素DataContext屬性內聲明爲DataContext的值。但在你的情況(因爲你沒有使用MVVM),你不應該這樣做。

相關問題