【问题标题】:Set DataContext in XAML在 XAML 中设置 DataContext
【发布时间】:2011-08-25 14:56:28
【问题描述】:

我有一个简单的应用程序,可以将一些项目添加到组合框中:

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 而不是在构造函数中初始化?

谢谢。

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    只需更改 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}}" ... />
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2014-07-06
        • 1970-01-01
        • 2013-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-29
        • 1970-01-01
        相关资源
        最近更新 更多