Skip to content

Property

Jordan Duerksen edited this page May 15, 2018 · 14 revisions

Property extends PropertySlim with the additional functionality seen below.

public class Property<TOwner, TValue> : PropertySlim<TValue>
{
    // added properties
    public bool IsDirty { get; set; } // True if Value has changed, otherwise false.  Set IsDirty to false manually to mark as clean.
    public TOwner Owner { get; set; } // The owner of this property, as determined by the constructor
    public TValue DefaultValue { get; set; }
	
    //added methods
    public void LoadValue(TValue value); //Sets the value without raising events or calling the constructor callback.  IsDirty is also reset to false.
    public void ResetToDefaultValue(bool raiseEvents); //sets the Value to DefaultValue raising events if raiseEvents is True
}
public class Property<TValue> : Property<Property<TValue>, TValue>
{
    //this class is just like Property<TOwner, TValue> except Owner is set to itself
}

Use

using System.Windows.Controls;
using W;

public class PersonControl : UserControl
{
    public Property<string> Name { get; } = new Property<string>();
    public Property<PersonControl, int> Age { get; private set; }

    public PersonControl()
    {
        InitializeComponent();

        Name.Value = "Jordan";

        // create the property, setting owner to this instance of PersonControl
        // set the initial value to a wishful age of 26 and pass in a ValueChanged callback
        Age = new Property<MyClass, int>(this, 26, (owner, oldValue, newValue) => { /* do something */ });
        Age.Value = 27;  // sets the Age.IsDirty flag to true
        Age.IsDirty = false; // manually mark as clean
        Age.LoadValue(28); // does not set Age.IsDirty flag
        ((IOwnedProperty)Age).SetOwner(someOtherObject); // sets the value of Owner to someOtherObject

        DataContext = this;
    }
}

As with PropertySlim, Property can be used for data binding in Xaml:

<TextBlock x:Name="txtName" Text="{Binding Path=Name.Value}" />
<Slider x:Name="sliderDesiredAge" Value="{Binding Path=Age.Value}" Minimum="0" Maximum="100" />

Clone this wiki locally