wpf 如何将实体从 Entity Framework 绑定到 DataGrid?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13277327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 06:07:12  来源:igfitidea点击:

How to bind entities from Entity Framework to DataGrid?

wpfentity-frameworkdata-bindingado.net

提问by pmichna

My XAML:

我的 XAML:

<Window x:Class="Newsletter.UI.MessagesWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MessagesWindow" Name="messagesWindow" Height="576" Width="1024" WindowStartupLocation="CenterScreen" Closed="MessagesWindowClosed">
    <Window.Resources>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Width" Value="149"/>
            <Setter Property="Margin" Value="10"/>
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="75"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel Grid.Row="0"  Orientation="Horizontal" HorizontalAlignment="Center">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <Button Name="saveButton" Grid.Row="0" Content="Save"  Margin="10,10,10,5"/>
                <TextBox Name="searchTextBox" Grid.Row="1"  Margin="10,5,10,10"/>
            </Grid>
            <Button Name="recipientsButton" Content="RECIPIENTS" Click="RecipientsButtonClick" />
            <Button Name="createButton" Content="CREATE" Click="CreateButtonClick" />
            <Button Name="removeButton" Content="REMOVE" />
            <Button Name="editButton" Content="EDIT" />
            <Button Name="resendButton" Content="RESEND"/>
        </StackPanel>
        <DataGrid Name="gridMessages" Grid.Row="1"/>
    </Grid>
</Window>

My .cs code:

我的 .cs 代码:

private void messagesWindow_Loaded(object sender, RoutedEventArgs e)
        {
            using (NewsletterEntities context = new NewsletterEntities())
            {
                var query = from m in context.Messages select m;
                var result = query.ToList();
                gridMessages.DataContext = result;
            }
        }

Messageclass generated by EF:

MessageEF 生成的类:

[EdmEntityTypeAttribute(NamespaceName="NewsletterModel", Name="Message")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class Message : EntityObject
{
    #region Factory Method

/// <summary>
/// Create a new Message object.
/// </summary>
/// <param name="messageID">Initial value of the MessageID property.</param>
/// <param name="subject">Initial value of the Subject property.</param>
/// <param name="content">Initial value of the Content property.</param>
/// <param name="hasAttachments">Initial value of the HasAttachments property.</param>
/// <param name="senderID">Initial value of the SenderID property.</param>
/// <param name="date">Initial value of the Date property.</param>
public static Message CreateMessage(global::System.Int32 messageID, global::System.String subject, global::System.String content, global::System.Boolean hasAttachments, global::System.Int32 senderID, global::System.DateTime date)
{
    Message message = new Message();
    message.MessageID = messageID;
    message.Subject = subject;
    message.Content = content;
    message.HasAttachments = hasAttachments;
    message.SenderID = senderID;
    message.Date = date;
    return message;
}

#endregion

#region Primitive Properties

/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 MessageID
{
    get
    {
        return _MessageID;
    }
    set
    {
        if (_MessageID != value)
        {
            OnMessageIDChanging(value);
            ReportPropertyChanging("MessageID");
            _MessageID = StructuralObject.SetValidValue(value);
            ReportPropertyChanged("MessageID");
            OnMessageIDChanged();
        }
    }
}
private global::System.Int32 _MessageID;
partial void OnMessageIDChanging(global::System.Int32 value);
partial void OnMessageIDChanged()

Unfortunately nothing happens, the DataGrid is empty. I'm new to data binding in WPF and EF. I hope this problem is simple but I have no idea how to solve it.

不幸的是什么也没发生,DataGrid 是空的。我是 WPF 和 EF 中数据绑定的新手。我希望这个问题很简单,但我不知道如何解决。

回答by McGarnagle

Instead of DataContext, set ItemsSourceto the result set.

而不是 DataContext,设置ItemsSource为结果集。

gridMessages.ItemsSource = result;


NoteSince you're new to WPF, you might want to note that MVVM is better than the approach here, for separating UI from business logic. To use an MVVM approach, you'd set your Window's DataContextto some View Model class:

注意由于您是 WPF 的新手,您可能需要注意 MVVM 比这里的方法更好,用于将 UI 与业务逻辑分离。要使用 MVVM 方法,您需要将 Window 设置DataContext为某个 View Model 类:

private void messagesWindow_Loaded(object sender, RoutedEventArgs e) 
{ 
    Model = new ViewModel();
    this.DataContext = Model;
    // TODO set Model.Messages to the EF result set
}

Where the ViewModel looks something like this:

ViewModel 看起来像这样:

public class ViewModel : INotifyPropertyChanged
{
    private List<Message> _messages;

    public List<Message> Messages
    {
        get { return _messages; }
        set
        {
            _messages = value;
            RaisePropertyChanged("Messages");
        }
    }

    // TODO implement INotifyPropertyChanged
}

Then bind the DataGrid's ItemsSource to your a property.

然后将 DataGrid 的 ItemsSource 绑定到您的属性。

<DataGrid ItemsSource="{Binding Messages}" Grid.Row="1"/>