2011-08-25 41 views
6

Tôi có ứng dụng này đơn giản mà bổ sung thêm một số mặt hàng vào một combobox:Set DataContext trong 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"); 
     } 
    } 

Và đây là file 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> 

Ai đó có thể chỉ cho tôi làm thế nào tôi có thể thiết lập DataContext từ tệp xaml thay vì khởi tạo trong hàm tạo?

Cảm ơn.

Trả lời

23

Chỉ cần thay đổi Window để ràng buộc DataContext với bản thân:

<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

Tôi tin rằng DataContext trong trường hợp này là ẩn và không cần phải được đặt kể từ khi bạn đang sử dụng mã phía sau. Nếu bạn đang sử dụng MVVM, bạn sẽ thêm một tham chiếu đến thư mục đó và lớp bên trong của bạn XAML đánh dấu và thiết lập khóa tài nguyên bằng một giá trị mà sau đó có thể được khai báo là DataContext bên trong của một phần tử con DataContext. Nhưng trong trường hợp của bạn (kể từ khi bạn không sử dụng MVVM) bạn không cần phải làm điều đó.

Các vấn đề liên quan