How can I add an “IsDirty” property to a LINQ to S

2019-02-19 10:09发布

问题:

I am binding my entities to an edit form in WPF. Within a DataTemplate, I want to be able to set the background color of the root container within a DataTemplate to show it has been changed and these changes have not yet been submitted to the database.

Here's a very simple sample that demonstrates what I'm talking about (forgive errors):

<Page ...>
    <Page.DataContext>
        <vm:MyPageViewModel /> <!-- Holds reference to the DataContext -->
    </Page.DataContext>
    <ItemsControl
        ItemsSource = {Binding Items}>
        <ItemsControl.Resources>
            <DataTemplate
                DataType="Lol.Models.Item"> <!-- Item is L2S entity -->
                <!-- In real life, I use styles to set the background color -->
                <TextBlock Text="{Binding IsDirty, StringFormat='Am I dirty? /{0/}'}"/>
            </DataTemplate>
        </ItemsControl.Resources>
    </ItemsControl>
</Page>

The example just prints out "Am I dirty? yes" or "Am I dirty? no", but you get the idea.

To do this, I'll need to add a public property to my Item (partial class, simple) that can determine if the entity is dirty or not. This is the tough bit.

public partial class Item
{
    public bool IsDirty
    {
        get
        {
            throw new NotImplementedException("hurf durf");
        }
    }
}

Outside of the entity, it's pretty simple (as long as you have the DataContext the entity is attached to). Inside, not so much.

What are my options here?


Edit: I don't think there's one good solution here, so suggestions for workarounds are welcome.

(Okay, similar questions exist, but they are all about how to determine this from outside of the entity itself and use the DataContext the entity is attached to.)

回答1:

If you are using the dbml generated classes, you should be able to implement a couple of partial methods like this:

public partial class SampleEntity
{
    partial void OnCreated()
    {
        this.IsDirty = true;
    }

    partial void OnLoaded()
    {
        this.PropertyChanged += (s, e) => this.IsDirty = true;
        this.IsDirty = false;
    }

    public bool IsDirty { get; private set; }
}