c# - 在 XAML 中而不是在代码隐藏中设置 DataContext

标签 c# wpf xaml

我在其他帖子中读到,可以在 XAML 中指定其背后的代码中指定 DataContext 的位置。

我在主类的构造函数中声明并填充了一个 ObservableCollection,我还设置了 DataContext:

using System;
using System.Windows;
using System.Collections.ObjectModel;

namespace ItemsControlDemo
{
    public partial class MainWindow : Window
    {
        public ObservableCollection<Person> PersonList { get; set; }

        public MainWindow()
        {
            InitializeComponent();

            PersonList = new ObservableCollection<Person>();

            PersonList.Add(new Person(16, "Abraham", "Lincoln"));
            PersonList.Add(new Person(32, "Franklin", "Roosevelt"));
            PersonList.Add(new Person(35, "John", "Kennedy"));
            PersonList.Add(new Person(2, "John", "Adams"));
            PersonList.Add(new Person(1, "George", "Washington"));
            PersonList.Add(new Person(7, "Andrew", "Jackson"));

            DataContext = this;
        }

        private void Button_Add_Click(object sender, RoutedEventArgs e)
        {
            PersonList.Add(new Person(3, "Thomas", "Jefferson"));
        }

        private void Button_Remove_Click(object sender, RoutedEventArgs e)
        {
            PersonList.Remove(TheDataGrid.SelectedItem as Person);
        }
    }

    public class Person
    {
        public Person() { }

        public Person(int id, string firstName, string lastName)
        {
            ID = id;
            FirstName = firstName;
            LastName = lastName;
        }

        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

如果我这样做,在我的应用程序中一切正常。

但是,如果我删除“DataContext = this;”来自构造函数,而是在我的应用程序的 Window 元素中设置 DataContext

        DataContext="{Binding RelativeSource={RelativeSource Self}}"

我没有得到任何数据。

这是我从代码隐藏中删除后设置 DataContext 的 XAML:

<Window x:Class="ItemsControlDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:ItemsControlDemo"
        Title="Items Control Demo" Height="350" Width="400"
        WindowStartupLocation="CenterScreen"
        DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <DataGrid Grid.Row="0" Name="TheDataGrid" SelectedValuePath="ID"
                  AutoGenerateColumns="False"
                  AlternatingRowBackground="Bisque"
                  ItemsSource="{Binding PersonList}">
            <DataGrid.Columns>
                <DataGridTextColumn Header="ID"         Binding="{Binding Path=ID}"/>
                <DataGridTextColumn Header="First Name" Binding="{Binding Path=FirstName}"/>
                <DataGridTextColumn Header="Last Name"  Binding="{Binding Path=LastName}"/>
            </DataGrid.Columns>
        </DataGrid>
        <StackPanel Grid.Row="1" Orientation="Horizontal"
                    HorizontalAlignment="Left" VerticalAlignment="Bottom">
            <Button Content="Add Item"    Margin="5" Click="Button_Add_Click"/>
            <Button Content="Remove Item" Margin="5" Click="Button_Remove_Click"/>
        </StackPanel>
    </Grid>
</Window>

如能对我做错的事情提供任何帮助,我们将不胜感激。

谢谢!

最佳答案

您需要在调用 InitializeComponent 之前设置您的源

编辑:实际上你只需要在 InitializeComponent 之前实例化它,因为它是一个 ObservableCollection,它实现了 INotifyCollectionChanged,所以如果你修改集合,你的网格将随着变化而更新。

public MainWindow()
    {
        PersonList = new ObservableCollection<Person>();
        InitializeComponent();
        PersonList.Add(new Person(16, "Abraham", "Lincoln"));
        PersonList.Add(new Person(32, "Franklin", "Roosevelt"));
        PersonList.Add(new Person(35, "John", "Kennedy"));
        PersonList.Add(new Person(2, "John", "Adams"));
        PersonList.Add(new Person(1, "George", "Washington"));
        PersonList.Add(new Person(7, "Andrew", "Jackson"));
    }

关于c# - 在 XAML 中而不是在代码隐藏中设置 DataContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26206612/

相关文章:

c# - 如何在 C# 中为文本着色

c# - RDLC 中的特定格式编号

c# - Xamarin - Java.Lang.Thread 与 System.Threading.Thread - 使用哪一个?

c# - 是否可以强制基于DependencyProperty的绑定(bind)以编程方式重新评估?

c# - 将按钮插入 NavigationViewItem UWP

wpf - 禁用 WPF Web 浏览器滚动条

c# - 如何在 Razor View 中将@model 指令更改为不同的模型?

.net - Visual Studio 2008 中缺少工作流项目模板

WPF如何继承带有颜色动画的样式来改变颜色

wpf - 公开依赖项属性