在XAML中设置DataContext

时间:2011-08-25 14:56:29

标签: c# wpf 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而不是在构造函数中初始化?

感谢。

2 个答案:

答案 0 :(得分:24)

只需更改Window即可将 DataContext 绑定到自身:

<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}}" ... />

答案 1 :(得分:0)

我相信这个场景中的DataContext是隐式的,因为你使用后面的代码所以不必设置。如果您使用的是MVVM,则可以在XAML标记内添加对该文件夹和类的引用,并将资源键设置为等于可以在子元素DataContext属性中声明为DataContext的值。但在你的情况下(因为你没有使用MVVM)你不应该这样做。

相关问题