INotifyPropertyChanged 实现不适用于 Entity Framework 4.1 导航属性

发布于 2024-12-05 23:35:40 字数 3731 浏览 0 评论 0原文

使用 EF 4.1,我添加了 INotifyPropertyChanged 接口,以便在属性更改时通知我的视图。

 public class Department : INotifyPropertyChanged
{
    public Department()
    {
        this.Courses = new ObservableCollection<Course>();
    }

    // Primary key
    public int DepartmentID { get; set; }
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            RaisePropertyChanged("Name");
        }
    }

    // Navigation property
    public virtual ObservableCollection<Course> Courses { get; private set; }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = this.PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

public class Course : INotifyPropertyChanged...

在主详细信息场景中,我有一个查找组合来更改部门: 实现 INotifyPropertyChanged 时,部门属性不会更新,但从 Department 和 Course 类中删除 INotifyPropertyChanged 实现会更新:

XAML

    <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <DataGrid 
        AutoGenerateColumns="False" 
        EnableRowVirtualization="True" 
        Height="173" 
        HorizontalAlignment="Left" 
        ItemsSource="{Binding CourceViewSource}" 
        x:Name="departmentDataGrid" 
        RowDetailsVisibilityMode="VisibleWhenSelected" 
        VerticalAlignment="Top" 
        Width="347">
        <DataGrid.Columns>
            <DataGridTextColumn x:Name="CourseID" Binding="{Binding Path=CourseID}" 
                            Header="CourseID" Width="SizeToHeader" />
            <DataGridTextColumn x:Name="nameColumn" Binding="{Binding Path=Title}" 
                            Header="Title" Width="SizeToHeader" />
            <DataGridTextColumn x:Name="nameColumnw" Binding="{Binding Path=Department.Name}" 
                            Header="Department" Width="SizeToHeader" />
        </DataGrid.Columns>
    </DataGrid>

        <ComboBox Grid.Row="1"
                  ItemsSource="{Binding DepartmentLookUp}"
                  SelectedItem="{Binding CourceViewSource/Department}"   />


    <Button Grid.Row="2" Content="Save" Click="Button_Click"/>
</Grid>

代码隐藏 ...

private SchoolEntities _context = new SchoolEntities();
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
    }

    public ICollectionView CourceViewSource { get; private set; }
    public ICollectionView DepartmentLookUp { get; private set; }

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        _context.Departments.Load();     
        _context.Courses.Load();

        DepartmentLookUp = new ListCollectionView(_context.Departments.Local);
        CourceViewSource= new ListCollectionView(_context.Courses.Local);

        RaisePropertyChanged(() => DepartmentLookUp);
        RaisePropertyChanged(() => CourceViewSource);
    }

...

我已经包含了问题的示例 这里

当在详细信息中选择一个部门时,主数据中的部门不会更新,当更改主数据上的学分百分比时,详细信息上的学分会更新。

现在更改 SchoolModel.cs,以便 Notify 类不实现 INotifyPropertyChanged 接口(公共类 Notify //: INotifyPropertyChanged):

在详细信息中选择一个部门时,主数据中的部门会更新,当更改掌握细节上的学分,不要更新。

我不明白,也许缺少一些东西才能让两者都工作?

Using EF 4.1 I added the INotifyPropertyChanged interface to notified my view when properties change.

 public class Department : INotifyPropertyChanged
{
    public Department()
    {
        this.Courses = new ObservableCollection<Course>();
    }

    // Primary key
    public int DepartmentID { get; set; }
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            RaisePropertyChanged("Name");
        }
    }

    // Navigation property
    public virtual ObservableCollection<Course> Courses { get; private set; }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = this.PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

public class Course : INotifyPropertyChanged...

In a Master Detail scenario I have a lookup combo to change the Department:
When the INotifyPropertyChanged is implemented the department property won’t update, but removing the INotifyPropertyChanged implementation from the Department and Course class it does:

XAML

    <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <DataGrid 
        AutoGenerateColumns="False" 
        EnableRowVirtualization="True" 
        Height="173" 
        HorizontalAlignment="Left" 
        ItemsSource="{Binding CourceViewSource}" 
        x:Name="departmentDataGrid" 
        RowDetailsVisibilityMode="VisibleWhenSelected" 
        VerticalAlignment="Top" 
        Width="347">
        <DataGrid.Columns>
            <DataGridTextColumn x:Name="CourseID" Binding="{Binding Path=CourseID}" 
                            Header="CourseID" Width="SizeToHeader" />
            <DataGridTextColumn x:Name="nameColumn" Binding="{Binding Path=Title}" 
                            Header="Title" Width="SizeToHeader" />
            <DataGridTextColumn x:Name="nameColumnw" Binding="{Binding Path=Department.Name}" 
                            Header="Department" Width="SizeToHeader" />
        </DataGrid.Columns>
    </DataGrid>

        <ComboBox Grid.Row="1"
                  ItemsSource="{Binding DepartmentLookUp}"
                  SelectedItem="{Binding CourceViewSource/Department}"   />


    <Button Grid.Row="2" Content="Save" Click="Button_Click"/>
</Grid>

Code Behind
...

private SchoolEntities _context = new SchoolEntities();
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
    }

    public ICollectionView CourceViewSource { get; private set; }
    public ICollectionView DepartmentLookUp { get; private set; }

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        _context.Departments.Load();     
        _context.Courses.Load();

        DepartmentLookUp = new ListCollectionView(_context.Departments.Local);
        CourceViewSource= new ListCollectionView(_context.Courses.Local);

        RaisePropertyChanged(() => DepartmentLookUp);
        RaisePropertyChanged(() => CourceViewSource);
    }

...

I have included a sample of the problem here.

When selecting a Department in the details the Department in the Master don't update, when changing the Credit % on the master the Credits on the detail gets updated.!

Now changing the SchoolModel.cs so that the Notify class don't implement the INotifyPropertyChanged interface (public class Notify //: INotifyPropertyChanged):

When selecting a Department in the details the Department in the Master DO update, when changing the Credit % on the master the Credits on the detail DON'T get updated.

Im not getting it maybe there is something missing to get both to work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

扛刀软妹 2024-12-12 23:35:40

我不太了解 C#,无法对此发表评论,但下面是我在 VB.NET 中实现的 INotifyPropertyChanged。我不检查处理程序状态,但无论如何都会引发事件。从来没有让我失望过。

Public Event PropertyChanged As PropertyChangedEventHandler _
    Implements INotifyPropertyChanged.PropertyChanged

Protected Sub OnPropertyChanged(ByVal info As String)
    RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
End Sub

Don't know C# well enough to coment on that, but below is my implementation of INotifyPropertyChanged in VB.NET. I do not check the handler status, but just raise the event regardless. Has never failed me.

Public Event PropertyChanged As PropertyChangedEventHandler _
    Implements INotifyPropertyChanged.PropertyChanged

Protected Sub OnPropertyChanged(ByVal info As String)
    RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
End Sub
仅此而已 2024-12-12 23:35:40

查看您上传的代码,问题似乎是您在代码后面 (CourceViewSource_CurrentChanged) 中有一个事件处理程序,它在 CreditPersentage 时设置 Credits 属性DataGrid 中的 code> 已更改,但没有对应的事件处理程序,当 Credits TextBox 更改时,该事件处理程序会设置 CreditPersentage

如果 CreditsCreditPersentage 之间的关系始终为 100,那么为这两个字段设置两个数据库列就没有多大意义。我会认为其中一个字段是“计算的”并且“依赖于”另一个字段,并直接在模型中表达这一点。在数据库中我只会存储其中一个值。它可能如下所示:

public class Course : Notify
{
    //...

    private double _credits; // only one backing field for both properties
    public double Credits
    {
        get { return _credits; }
        set
        {
            _credits = value;
            RaisePropertyChanged(() => Credits);
            RaisePropertyChanged(() => CreditPersentage);
            // notify WPF that also CreditPersentage has changed now
        }
    }

    [NotMapped] // add using System.ComponentModel.DataAnnotations; for this
    public double CreditPersentage
    {
        get { return _credits / 100; }
        set
        {
            _credits = value * 100;
            RaisePropertyChanged(() => Credits);
            // notify WPF that also Credit has changed now
            RaisePropertyChanged(() => CreditPersentage);
        }
    }

    public int DepartmentID { get; set; }

    // also add change notification to Department
    private Department _department;
    public virtual Department Department
    {
        get { return _department; }
        set
        {
            _department = value;
            RaisePropertyChanged(() => Department);
        }
    }
}

[NotMapped] 属性确保数据库中没有 CreditPersentage 列。此属性只是根据 _credits 字段在内存中计算。

然后你可以删除后面代码中的CourceViewSource_CurrentChanged。对于您的文本框,您可以添加一个 UpdateSourceTrigger

<TextBox Grid.Row="4" Grid.Column="1"
         Text="{Binding Path=CourceViewSource/Credits,
                UpdateSourceTrigger=PropertyChanged}" />

现在应该可以编辑 DataGrid 中的百分比(文本框在您写入时更新)和文本框中的 Credits 值(百分比列当您写入时,DataGrid 会更新)。当您在组合框中选择一个新条目时,DataGrid 中的“部门”列将会更新。

Looking into the code you have uploaded the problem seems to be that you have an event handler in code behind (CourceViewSource_CurrentChanged) which sets the Credits property when CreditPersentage in the DataGrid is changed but there is not the counterpart - an event handler which sets the CreditPersentage when the Credits TextBox is changed.

If your relationship between Credits and CreditPersentage is always a factor of 100 then it doesn't make much sense to have two database columns for both fields. I would consider one of the fields as "calculated" and "dependent" on the other and directly express this in the model. In the database I would store only one of the values. It could look like this:

public class Course : Notify
{
    //...

    private double _credits; // only one backing field for both properties
    public double Credits
    {
        get { return _credits; }
        set
        {
            _credits = value;
            RaisePropertyChanged(() => Credits);
            RaisePropertyChanged(() => CreditPersentage);
            // notify WPF that also CreditPersentage has changed now
        }
    }

    [NotMapped] // add using System.ComponentModel.DataAnnotations; for this
    public double CreditPersentage
    {
        get { return _credits / 100; }
        set
        {
            _credits = value * 100;
            RaisePropertyChanged(() => Credits);
            // notify WPF that also Credit has changed now
            RaisePropertyChanged(() => CreditPersentage);
        }
    }

    public int DepartmentID { get; set; }

    // also add change notification to Department
    private Department _department;
    public virtual Department Department
    {
        get { return _department; }
        set
        {
            _department = value;
            RaisePropertyChanged(() => Department);
        }
    }
}

The [NotMapped] attribute makes sure that there is no CreditPersentage column in the database. This property is just calculated in memory based on the _credits field.

Then you can remove the CourceViewSource_CurrentChanged in the code behind. And for your textbox you could add an UpdateSourceTrigger:

<TextBox Grid.Row="4" Grid.Column="1"
         Text="{Binding Path=CourceViewSource/Credits,
                UpdateSourceTrigger=PropertyChanged}" />

It should now be possible to edit the percentage in the DataGrid (the textbox gets updated when you write) and the Credits value in the textbox (the percentage column in the DataGrid gets updated when you write). And when you select a new entry in the comboxbox the Department column in the DataGrid gets updated.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文