在XAML中设置DataContext

7
我有一个简单的应用程序,可以将一些项目添加到下拉框中:
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个回答

25

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

0

我认为在这种情况下,DataContext是隐式的,不需要设置,因为您正在使用代码后台。如果您正在使用MVVM,则会在XAML标记中添加对该文件夹和类的引用,并将资源键设置为可以声明为子元素DataContext属性内部的DataContext的值。但在您的情况下(因为您没有使用MVVM),您不应该这样做。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接