设置的DataContext在XAML [英] Set DataContext in XAML

查看:109
本文介绍了设置的DataContext在XAML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的应用程序,增加了一些资料转移到组合框:

I have this simple application that adds some items to a combobox:

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文件:

And here is the XAML file:

<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?

Can someone show me how can I set the DataContext from the xaml file instead of initializing in the constructor ?

感谢。

推荐答案

只要改变窗口绑定的 的DataContext 的本身:

Just change the Window to bind DataContext to itself:

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

这篇关于设置的DataContext在XAML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆