2011-08-25 65 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),你不应该这样做。

相关问题