WPF EditableObject

Introduction

EditableObject is designed as an advanced view model property editor. It encapsulates dirty/edited/originalValue etc.. functions within properties of Model(TObj). So that binding EditableProperty in UI can easily notify when value is changed, or rollback to original value, or save value.

This object use Linq Expression and Reflection to get or set values of an object.
While I'm writing this, my c# version has no support for nameof keyword, so I have to use Linq Expression instead, or there will be a more flexible and clear codes.

Usage ViewModel

    public partial class EditableObjectTest : ViewModelBase
    {
        public EditableObject<Person, string> EditablePerson { get; }
        public EditableProperty<string> EditableFirstName => EditablePerson[() => Model.FirstName];
        public EditableProperty<string> EditableLastName => EditablePerson[() => Model.LastName];
        public EditableProperty<string> EditableAddress => EditablePerson[() => Model.Address];
        public Person Model { get; set; }
        public EditableObjectTest()
        {
            Model = new Person {FirstName = "Z", LastName = "w", Address = "1003No"};

            EditablePerson = new EditableObject<Person, string>(Model,
                new Expression<Func<string>>[] //System.Linq.Expressions.Expression
                {
                    () => Model.FirstName,
                    () => Model.LastName,
                    () => Model.Address,
                } );
            EditablePerson.PropertyChanged += property => { };
        }
    }

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
    }

Usage of UI

        <TextBox  Text="{Binding EditableFirstName.Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
            <TextBox.Style>
                <Style>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding EditableFirstName.IsDirty}" Value="True">
                            <Setter Property="TextBox.Background" Value="Yellow"></Setter>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBox.Style>
        </TextBox>

Object Structure

    public class EditableObject<TObj, TValue>
    {
        private bool _canMarkDirty;

        public event Action<EditableProperty<TValue>> PropertyChanged;

        public TObj SourceObject { get; }
        public Dictionary<string, EditableProperty<TValue>> PropertyDictionary { get; }

        /// <summary>
        /// A flag that determines whether each editable property can be marked as modified or not if value is changed.
        /// </summary>
        public bool CanMarkDirty
        {
            get { return _canMarkDirty; }
            set
            {
                _canMarkDirty = value;
                foreach (var prop in PropertyDictionary.Values)
                {
                    prop.CanMarkDirty = value;
                }
            }
        }

        public EditableObject(TObj sourceObj, IEnumerable<Expression<Func<TValue>>> propExpressions)
        {
            SourceObject = sourceObj;
            PropertyDictionary = new Dictionary<string, EditableProperty<TValue>>();
            foreach (var propExp in propExpressions)
            {
                var propInfo = ExtractExpressionToPropInfo(propExp);
                if (propInfo == null)
                {
                    continue;
                }

                var key = propInfo.Name;
                var getValueFunc = propExp.Compile();
                var value = getValueFunc();

                var newProp = new EditableProperty<TValue>(value);
                newProp.ValueChanged += sender =>
                {
                    SetEditedValue(sender, sourceObj);
                    PropertyChanged?.Invoke(sender);
                };

                PropertyDictionary.Add(key, newProp);
            }
        }

        /// <summary>
        /// Checks if there're properties that are modified.
        /// </summary>
        public bool ContainsModifications()
        {
            return PropertyDictionary.Values.Any(o => o.IsDirty);
        }

        /// <summary>
        /// Sets modified property value to to specific object.
        /// </summary>
        public void SetEditedValue(EditableProperty<TValue> editableProp, TObj targetObj)
        {
            var key = PropertyDictionary.First(p => p.Value == editableProp).Key;
            typeof(TObj).GetProperty(key).SetValue(targetObj, editableProp.Value);
        }

        /// <summary>
        /// Sets all modified property values to to specific object.
        /// </summary>
        public void SetEditedValuesTo(TObj targetObj)
        {
            foreach (var prop in PropertyDictionary.Values)
            {
                SetEditedValue(prop, targetObj);
            }
        }

        /// <summary>
        /// Saves all <see cref="EditableProperty{T}"/>s' values (including setting original value and reset modified flag).
        /// </summary>
        public void SaveChanges()
        {
            foreach (var prop in PropertyDictionary.Values)
            {
                prop.SaveValue();
            }
        }

        /// <summary>
        /// Discards all <see cref="EditableProperty{T}"/>s' values (including setting original value and reset modified flag).
        /// </summary>
        public void DiscardChanges()
        {
            foreach (var prop in PropertyDictionary.Values)
            {
                prop.ResetValue();
            }
        }

        /// <summary>
        /// Extracts <see cref="PropertyInfo"/> from property expression.
        /// </summary>
        private PropertyInfo ExtractExpressionToPropInfo(Expression<Func<TValue>> propExpression)
        {
            var propInfo = (propExpression.Body as MemberExpression)?.Member as PropertyInfo;
            if (propInfo == null)
            {
                Console.WriteLine("EditableObjectCollection ExtractExpressionToPropInfo failed: Cannot resolve expression: {0}", propExpression.Name);
            }
            return propInfo;
        }

        /// <summary>
        /// The Indexer that gets <see cref="EditableProperty{T}"/> via specific property expression.
        /// </summary>
        public EditableProperty<TValue> this[Expression<Func<TValue>> propExpression] => PropertyDictionary[ExtractExpressionToPropInfo(propExpression).Name];
    }

    public class EditableProperty<T> : ObservableObject
    {
        private T _value;
        private T _originalValue;
        private bool _isDirty;
        private bool _canMarkDirty;

        public event Action<EditableProperty<T>> ValueChanged;

        /// <summary>
        /// Please use SetValue method instead of Property-Setter.
        /// </summary>

        public T Value
        {
            get { return _value; }
            set
            {
                _value = value;
                RaisePropertyChanged(() => Value);
                if (CanMarkDirty)
                {
                    //special case: string.Empty and null is regarded as same.
                    if (typeof(T) == typeof(string) &&
                        string.IsNullOrEmpty(Value as string) &&
                        string.IsNullOrEmpty(OriginalValue as string))
                    {
                        IsDirty = false;
                    }
                    else
                    {
                        IsDirty = !Equals(Value, OriginalValue);
                    }
                }
                ValueChanged?.Invoke(this);
            }
        }


        /// <summary>
        /// The original value for value modification comparison.
        /// </summary>
        public T OriginalValue
        {
            get { return _originalValue; }
            set
            {
                _originalValue = value;
                RaisePropertyChanged(() => OriginalValue);
            }
        }

        /// <summary>
        /// Determines if value is modified.
        /// </summary>
        public bool IsDirty
        {
            get { return _isDirty; }
            set
            {
                _isDirty = value;
                RaisePropertyChanged(() => IsDirty);
            }
        }

        /// <summary>
        /// A flag that determines whether this property can be marked as modified or not if value is changed.
        /// </summary>
        public bool CanMarkDirty
        {
            get { return _canMarkDirty; }
            set
            {
                _canMarkDirty = value;
                RaisePropertyChanged(() => CanMarkDirty);
            }
        }

        public EditableProperty(T value)
        {
            Value = value;
            OriginalValue = value;
            IsDirty = false;
            CanMarkDirty = true;
        }

        /// <summary>
        /// Saves the value modification so that original value is consistent with value and modified flag is false.
        /// </summary>
        public void SaveValue()
        {
            OriginalValue = Value;
            IsDirty = false;
        }

        /// <summary>
        /// Discards the value modification so that original value is consistent with value and modified flag is false.
        /// </summary>
        public void ResetValue()
        {
            Value = OriginalValue;
            IsDirty = false;
        }
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末节吮,一起剝皮案震驚了整個濱河市渠驼,隨后出現(xiàn)的幾起案子滴劲,更是在濱河造成了極大的恐慌暇务,老刑警劉巖苛秕,帶你破解...
    沈念sama閱讀 222,000評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異摄杂,居然都是意外死亡左腔,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,745評論 3 399
  • 文/潘曉璐 我一進店門懂拾,熙熙樓的掌柜王于貴愁眉苦臉地迎上來煤禽,“玉大人,你說我怎么就攤上這事岖赋∶使” “怎么了?”我有些...
    開封第一講書人閱讀 168,561評論 0 360
  • 文/不壞的土叔 我叫張陵唐断,是天一觀的道長选脊。 經(jīng)常有香客問我,道長脸甘,這世上最難降的妖魔是什么恳啥? 我笑而不...
    開封第一講書人閱讀 59,782評論 1 298
  • 正文 為了忘掉前任,我火速辦了婚禮丹诀,結(jié)果婚禮上钝的,老公的妹妹穿的比我還像新娘。我一直安慰自己铆遭,他們只是感情好硝桩,可當(dāng)我...
    茶點故事閱讀 68,798評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著枚荣,像睡著了一般碗脊。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上橄妆,一...
    開封第一講書人閱讀 52,394評論 1 310
  • 那天望薄,我揣著相機與錄音疟游,去河邊找鬼。 笑死痕支,一個胖子當(dāng)著我的面吹牛颁虐,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播卧须,決...
    沈念sama閱讀 40,952評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼另绩,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了花嘶?” 一聲冷哼從身側(cè)響起笋籽,我...
    開封第一講書人閱讀 39,852評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎椭员,沒想到半個月后车海,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,409評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡隘击,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,483評論 3 341
  • 正文 我和宋清朗相戀三年侍芝,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片埋同。...
    茶點故事閱讀 40,615評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡州叠,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出凶赁,到底是詐尸還是另有隱情咧栗,我是刑警寧澤,帶...
    沈念sama閱讀 36,303評論 5 350
  • 正文 年R本政府宣布虱肄,位于F島的核電站致板,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏咏窿。R本人自食惡果不足惜可岂,卻給世界環(huán)境...
    茶點故事閱讀 41,979評論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望翰灾。 院中可真熱鬧缕粹,春花似錦、人聲如沸纸淮。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,470評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽咽块。三九已至绘面,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背揭璃。 一陣腳步聲響...
    開封第一講書人閱讀 33,571評論 1 272
  • 我被黑心中介騙來泰國打工晚凿, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人瘦馍。 一個月前我還...
    沈念sama閱讀 49,041評論 3 377
  • 正文 我出身青樓歼秽,卻偏偏與公主長得像,于是被迫代替她去往敵國和親情组。 傳聞我的和親對象是個殘疾皇子燥筷,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,630評論 2 359

推薦閱讀更多精彩內(nèi)容