Edit: This is a simplified update of the original version of this post.
In WPF I implemented a UserControl (called 'NumericTextBox') which uses a *DependencyProperty 'Value' that is kept in sync with the Text property of a TextBox (xaml):
<TextBox.Text>
<Binding Path="Value"
Mode="TwoWay"
ValidatesOnDataErrors="True"
NotifyOnValidationError="True"
UpdateSourceTrigger="PropertyChanged" />
</TextBox.Text>
For validation purposes I use the IDataErrorInfo interface (xaml.cs):
public partial class NumericTextbox : Textbox, IDataErrorInfo {
public double Value {
get { return (double)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(double),
typeof(NumericTextBox),
new PropertyMetadata(default(double)));
public string this[string columnName]
{
// Never gets called!
get { /* Some validation rules here */ }
}
}
As stated in the source code, the get property actually never gets called, hence no validation happens. Do you see the reason for the problem?
Edit2: Based on ethicallogics' answer I restructered my code. The NumericTextBox now uses an underlying viewmodel class which provides a Dependency Property Value that is bound to the Text property of the TextBox which is declared by NumericTextBox. Additionally NumericTextBox uses the viewmodel as its datacontext. The viewmodel is now responsible for checking changes of the Value property. As the value restrictions of NumericTextBox are customizable (e.g. the Minimum can be adapted) it forwards these settings to the viewmodel object.
Do it like this rather than creating any Dependency Property . Validations are applied at ViewModel not in Control or View . Try it like this I hope this will help.
public class MyViewModel : INotifyPropertyChanged, IDataErrorInfo
{
public MyViewModel()
{
Value = 30;
}
private double _value;
[Range(1, 80, ErrorMessage = "out of range")]
public double Value
{
get
{
return _value;
}
set
{
_value = value;
ValidationMessageSetter("Value", value);
}
}
private void ValidationMessageSetter(string propertyName, object value)
{
Notify(propertyName);
string validationresult = ValidateProperty(propertyName, value);
if (!string.IsNullOrEmpty(validationresult) && !_dataErrors.ContainsKey(propertyName))
_dataErrors.Add(propertyName, validationresult);
else if (_dataErrors.ContainsKey(propertyName))
_dataErrors.Remove(propertyName);
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
private void Notify(string str)
{
if(PropertyChanged!=null)
PropertyChanged(this,new PropertyChangedEventArgs(str));
}
private string ValidateProperty(string propertyName,object value)
{
var results = new List<ValidationResult>(2);
string error = string.Empty;
bool result = Validator.TryValidateProperty(
value,
new ValidationContext(this, null, null)
{
MemberName = propertyName
},
results);
if (!result && (value == null || ((value is int || value is long) && (int)value == 0) || (value is decimal && (decimal)value == 0)))
return null;
if (!result)
{
ValidationResult validationResult = results.First();
error = validationResult.ErrorMessage;
}
return error;
}
#region IDataErrorInfo Members
private Dictionary<string, string> _dataErrors = new Dictionary<string, string>();
public string Error
{
get { throw new NotImplementedException(); }
}
public string this[string columnName]
{
get
{
if (_dataErrors.ContainsKey(columnName))
return _dataErrors[columnName];
else
return null;
}
}
#endregion
}
<TextBox Text="{Binding Value, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"/>
I hope this will help.
The IDataErrorInfo interface should be implemented on the object that is being bound to, not on the object that has the DependencyProperty.
In your example, if you want to get validation using this mechanism then your view model needs to do something like the below for the Value property:
public class ViewModel : IDataErrorInfo
{
public string this[string columnName]
{
// Never gets called!
get
{
if (columnName == "Value")
return GetValidationMessageForValueField();
return null;
}
}
}
I'm guessing that what you actually want to do is to validate when someone enters a non-numeric value in the TextBox..? If this is the case the you probably want to take a different approach than using IDataErrorInfo
Related
I have a ViewModel which works in UWP, all bindings are working except my custom dictionary and I don't know why. Nothing shows up.
I'm using FodyWeavers hence the shorthand notation. The custom dictionary returns the key with a * behind it if the key isn't found.
In the ViewModel
public static TranslationDictionary Translations { get; set; }
In the view
<TextBlock Text="{Binding Translations[Test_Translation]}" />
Custom Dictionary
public class TranslationDictionary : Dictionary<string, string>
{
public new void Add(string key, string value)
{
if (value == null)
{
return;
}
base.Add(key, value);
}
public new void Remove(string key)
{
if (!ContainsKey(key))
{
return;
}
base.Remove(key);
}
public new string this[string key]
{
get
{
string value;
return TryGetValue(key, out value) ? value : key + "*";
}
set
{
if (value == null)
{
Remove(key);
}
else
{
base[key] = value;
}
}
}
}
You could achieve this result by using x:Bind instead of Binding
An overview of the difference between x:Bind & Binding here
And so declaring a static class looking like that :
public static class DictionariesOperations
{
public static string GetValue(Dictionary<string, string> dict, string key)
{
return dict[key];
}
}
And then in your xaml :
<TextBlock Text="{x:Bind local:DictionariesOperations.GetValue(Translations, Test_Translation)}" />
Hope this help =)
I'm trying to implement some kind of Object Picker in WPF. So far I've created the Window with a DataGrid which ItemsSource is bound to an ObservableCollection. I also set AutoGenerateColumns to 'true' due to the fact that the Item to be picked can be any kind ob object.
The Objects inside the Collection are wrapped in a SelectionWrapper< T> which contains an IsSelected Property in order to select them.
class SelectionWrapper<T> : INotifyPropertyChanged
{
// Following Properties including PropertyChanged
public bool IsSelected { [...] }
public T Model { [...] }
}
I also added a CustomColumn to the DataGrid.Columns in order to bind the IsSelected Property like so
<DataGrid AutoGenerateColumns="True" ItemsSource="{Binding SourceView}">
<DataGrid.Columns>
<DataGridCheckBoxColumn Header="Selected" Binding="{Binding IsSelected}" />
</DataGrid.Columns>
</DataGrid>
The result I get with this solution is not very satisfying because there is just my defined Column 'Selected' and two GeneratedColumns 'IsSelected' and 'Model'.
Is there a way to change the target for the AutoGeneration to display all Properties of Model instead?
Also it is necessary to make the AutoGeneratedColumns ReadOnly because no one should edit the displayed Entries.
It is no option to turn off AutoGenerateColumns and add some more manual Columns like
<DataGridTextColumn Binding="{Binding Model.[SomeProperty]}"/>
because the Model can be of any kind of Object. Maybe there is a way to route the target for AutoGeneration to the Model Property?
Thanks in Advance
Edit
After accepting the Answer of #grek40
I came up with the following
First I created a general class of SelectionProperty which is inherited in SelectionProperty<T>. Here I implement the Interface ICustomTypeDescriptor which finally looked like:
public abstract class SelectionProperty : NotificationalViewModel, ICustomTypeDescriptor
{
bool isSelected = false;
public bool IsSelected
{
get { return this.isSelected; }
set
{
if (this.isSelected != value)
{
this.isSelected = value;
this.OnPropertyChanged("IsSelected");
}
}
}
object model = null;
public object Model
{
get { return this.model; }
set
{
if (this.model != value)
{
this.model = value;
this.OnPropertyChanged("Model");
}
}
}
public SelectionProperty(object model)
{
this.Model = model;
}
#region ICustomTypeDescriptor
[...]
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return TypeDescriptor.GetProperties(this.Model.GetType());
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
if (pd.DisplayName == "IsSelected")
return this;
return this.Model;
}
#endregion
Then I created a specialized ObservableCollection
class SelectionPropertyCollection<T> : ObservableCollection<T>, ITypedList
where T : SelectionProperty
{
public SelectionPropertyCollection(IEnumerable<T> collection) : base(collection)
{
}
public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
{
return TypeDescriptor.GetProperties(typeof(T).GenericTypeArguments[0]);
}
public string GetListName(PropertyDescriptor[] listAccessors)
{
return null;
}
}
Well and the last thing is the ViewModel. The most significant lines are
class ObjectPickerViewModel<ObjectType> : BaseViewModel
{
public ICollectionView SourceView { get; set; }
SelectionPropertyCollection<SelectionProperty<ObjectType>> source = null;
public SelectionPropertyCollection<SelectionProperty<ObjectType>> Source
{
get { return this.source; }
set
{
if (this.source != value)
{
this.source = value;
this.OnPropertyChanged("Source");
}
}
}
// [...]
this.Source = new SelectionPropertyCollection<SelectionProperty<ObjectType>>(source.Select(x => new SelectionProperty<ObjectType>(x)));
this.SourceView = CollectionViewSource.GetDefaultView(this.Source);
}
The good thing here is, that I can still add more Columns in the XAML but also have all public Properties of the Wrapped Object!
Following the course of Binding DynamicObject to a DataGrid with automatic column generation?, the following should work to some extent but I'm not quite sure if I would ever use something like it in production:
Create a collection that implements ITypedList and IList. GetItemProperties from ITypedList will be used. Expect the list type to implement ICustomTypeDescriptor:
public class TypedList<T> : List<T>, ITypedList, IList
where T : ICustomTypeDescriptor
{
public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
{
if (this.Any())
{
return this[0].GetProperties();
}
return new PropertyDescriptorCollection(new PropertyDescriptor[0]);
}
public string GetListName(PropertyDescriptor[] listAccessors)
{
return null;
}
}
Implement SelectionWrapper<T> as DynamicObject and implement ICustomTypeDescriptor (at least the PropertyDescriptorCollection GetProperties() method)
public class SelectionWrapper<T> : DynamicObject, INotifyPropertyChanged, ICustomTypeDescriptor
{
private bool _IsSelected;
public bool IsSelected
{
get { return _IsSelected; }
set { SetProperty(ref _IsSelected, value); }
}
private T _Model;
public T Model
{
get { return _Model; }
set { SetProperty(ref _Model, value); }
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (Model != null)
{
var prop = typeof(T).GetProperty(binder.Name);
// indexer member will need parameters... not bothering with it
if (prop != null && prop.CanRead && prop.GetMethod != null && prop.GetMethod.GetParameters().Length == 0)
{
result = prop.GetValue(Model);
return true;
}
}
return base.TryGetMember(binder, out result);
}
public override IEnumerable<string> GetDynamicMemberNames()
{
// not returning the Model property here
return typeof(T).GetProperties().Select(x => x.Name).Concat(new[] { "IsSelected" });
}
public PropertyDescriptorCollection GetProperties()
{
var props = GetDynamicMemberNames();
return new PropertyDescriptorCollection(props.Select(x => new DynamicPropertyDescriptor(x, GetType(), typeof(T))).ToArray());
}
// some INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChangedEvent([CallerMemberName]string prop = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(prop));
}
protected bool SetProperty<T2>(ref T2 store, T2 value, [CallerMemberName]string prop = null)
{
if (!object.Equals(store, value))
{
store = value;
RaisePropertyChangedEvent(prop);
return true;
}
return false;
}
// ... A long list of interface method implementations that just throw NotImplementedException for the example
}
The DynamicPropertyDescriptor hacks a way to access the properties of the wrapper and the wrapped object.
public class DynamicPropertyDescriptor : PropertyDescriptor
{
private Type ObjectType;
private PropertyInfo Property;
public DynamicPropertyDescriptor(string name, params Type[] objectType) : base(name, null)
{
ObjectType = objectType[0];
foreach (var t in objectType)
{
Property = t.GetProperty(name);
if (Property != null)
{
break;
}
}
}
public override object GetValue(object component)
{
var prop = component.GetType().GetProperty(Name);
if (prop != null)
{
return prop.GetValue(component);
}
DynamicObject obj = component as DynamicObject;
if (obj != null)
{
var binder = new MyGetMemberBinder(Name);
object value;
obj.TryGetMember(binder, out value);
return value;
}
return null;
}
public override void SetValue(object component, object value)
{
var prop = component.GetType().GetProperty(Name);
if (prop != null)
{
prop.SetValue(component, value);
}
DynamicObject obj = component as DynamicObject;
if (obj != null)
{
var binder = new MySetMemberBinder(Name);
obj.TrySetMember(binder, value);
}
}
public override Type PropertyType
{
get { return Property.PropertyType; }
}
public override bool IsReadOnly
{
get { return !Property.CanWrite; }
}
public override bool CanResetValue(object component)
{
return false;
}
public override Type ComponentType
{
get { return typeof(object); }
}
public override void ResetValue(object component)
{
}
public override bool ShouldSerializeValue(object component)
{
return false;
}
}
public class MyGetMemberBinder : GetMemberBinder
{
public MyGetMemberBinder(string name)
: base(name, false)
{
}
public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
{
throw new NotImplementedException();
}
}
public class MySetMemberBinder : SetMemberBinder
{
public MySetMemberBinder(string name)
: base(name, false)
{
}
public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, DynamicMetaObject value, DynamicMetaObject errorSuggestion)
{
throw new NotImplementedException();
}
}
Now if you bind some TypedList<SelectionWrapper<ItemViewModel>> to your datagrid itemssource, it should populate the columns for IsSelected and for the properties of ItemViewModel.
Let me say it again - the whole approach is a bit hacky and my implementation here is far from being stable.
As I think about it some more, there is probably no real need for the whole DynamicObject stuff as long as the TypedList is used to define the columns and some DynamicPropertyDescriptor to access the properties from wrapper and model.
Is there a way to change the target for the AutoGeneration to display all Properties of Model instead?
Short answer: No.
Only a column per public property of the type T of the IEnumerable<T> that you set as the ItemsSource will be created.
You should consider setting the AutoGenerateColumns property to false and creating the columns programmatically instead of hard-coding them in your XAML markup.
In XAML (specifically on Universal Windows Platform) I can data bind to an indexed property using the property path notation for indexers.
e.g. Given a data source of type Dictionary<string,string> I can bind to an indexed property as follows:
<TextBlock Text="{Binding Dictionary[Property]}"/>
In the above, the TextBlock's DataContext is set to an object with a dictionary property, say the following:
public class DataObject
{
public Dictionary<string,string> Dictionary { get; } = new Dictionary<string,string> {["Property"]="Value"};
}
My question is, is it possible to bind to the indexed property without using the indexer notation, but instead using the syntax for standard property binding?
i.e.
<TextBlock Text="{Binding Dictionary.Property}"/>
From my initial tests this doesn't seem to work. Is there an easy way to make it work? I want to use a data source object with an indexed property (like the Dictionary in this case but could just be a simple object). I don't want to use dynamic objects.
There is no syntax that does what you want, I'm afraid. The syntax for standard property binding works for standard properties, e.g.,
<TextBlock Text="{Binding Dictionary.Count}" />
...will bind to the Count property of the dictionary (or whatever object). You need them brackets...
EDIT
If you really hate the brackets, the closest thing I can find would be to use a converter with a parameter. For example:
public class MyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
IDictionary<string, string> dictionary = value as IDictionary<string, string>;
string dictionaryValue;
if (dictionary != null && dictionary.TryGetValue(parameter as string, out dictionaryValue))
{
return dictionaryValue;
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotSupportedException();
}
}
XAML:
<Page
x:Class="UWP.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:uwp="using:UWP">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.Resources>
<uwp:MyConverter x:Key="MyConverter" />
</Grid.Resources>
<Grid.DataContext>
<uwp:DataObject />
</Grid.DataContext>
<TextBlock
Text="{Binding Dictionary, ConverterParameter=Property1, Converter={StaticResource MyConverter}}" />
</Grid>
</Page>
...which is a roundabout way of ending up with something harder to read than the brackets.
A long time ago there was this ObservableDictionary class in Windows 8 app templates that does what you want. It's not a Dictionary<string, string>, but you can copy values from your Dictionary into the ObservableDictionary
Usage
Declare an ObservableDictionary property in your ViewModel, then bind to its indexer like usual properties:
using System;
using System.Collections.Generic;
using System.Linq;
using Windows.Foundation.Collections;
namespace MyApp
{
public class ObservableDictionary : IObservableMap<string, object>
{
private class ObservableDictionaryChangedEventArgs : IMapChangedEventArgs<string>
{
public ObservableDictionaryChangedEventArgs(CollectionChange change, string key)
{
this.CollectionChange = change;
this.Key = key;
}
public CollectionChange CollectionChange { get; private set; }
public string Key { get; private set; }
}
private Dictionary<string, object> _dictionary = new Dictionary<string, object>();
public event MapChangedEventHandler<string, object> MapChanged;
private void InvokeMapChanged(CollectionChange change, string key)
{
var eventHandler = MapChanged;
if (eventHandler != null)
{
eventHandler(this, new ObservableDictionaryChangedEventArgs(change, key));
}
}
public void Add(string key, object value)
{
this._dictionary.Add(key, value);
this.InvokeMapChanged(CollectionChange.ItemInserted, key);
}
public void Add(KeyValuePair<string, object> item)
{
this.Add(item.Key, item.Value);
}
public bool Remove(string key)
{
if (this._dictionary.Remove(key))
{
this.InvokeMapChanged(CollectionChange.ItemRemoved, key);
return true;
}
return false;
}
public bool Remove(KeyValuePair<string, object> item)
{
object currentValue;
if (this._dictionary.TryGetValue(item.Key, out currentValue) &&
Object.Equals(item.Value, currentValue) && this._dictionary.Remove(item.Key))
{
this.InvokeMapChanged(CollectionChange.ItemRemoved, item.Key);
return true;
}
return false;
}
public virtual object this[string key]
{
get
{
return this._dictionary[key];
}
set
{
this._dictionary[key] = value;
this.InvokeMapChanged(CollectionChange.ItemChanged, key);
}
}
public void Clear()
{
var priorKeys = this._dictionary.Keys.ToArray();
this._dictionary.Clear();
foreach (var key in priorKeys)
{
this.InvokeMapChanged(CollectionChange.ItemRemoved, key);
}
}
public ICollection<string> Keys
{
get { return this._dictionary.Keys; }
}
public bool ContainsKey(string key)
{
return this._dictionary.ContainsKey(key);
}
public bool TryGetValue(string key, out object value)
{
return this._dictionary.TryGetValue(key, out value);
}
public ICollection<object> Values
{
get { return this._dictionary.Values; }
}
public bool Contains(KeyValuePair<string, object> item)
{
return this._dictionary.Contains(item);
}
public int Count
{
get { return this._dictionary.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
return this._dictionary.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this._dictionary.GetEnumerator();
}
public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
{
int arraySize = array.Length;
foreach (var pair in this._dictionary)
{
if (arrayIndex >= arraySize) break;
array[arrayIndex++] = pair;
}
}
}
}
class DictionaryXamlWrapper : DynamicObject, INotifyPropertyChanged
{
#region PropertyChangedFunctional
public void OnPropertyChanged([CallerMemberName] string aProp = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(aProp));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
Dictionary<string, object> members = new Dictionary<string, object>();
// установка свойства
public override bool TrySetMember(SetMemberBinder binder, object value)
{
members[binder.Name] = value;
OnPropertyChanged(binder.Name);
return true;
}
// получение свойства
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = null;
if (members.ContainsKey(binder.Name))
{
result = members[binder.Name];
return true;
}
return false;
}
}
Of course, you can delete INotifyPropertyChanged functional if you do not need it.
And usage as you wanted
<TextBlock Text="{Binding DictionaryXamlWrapper.TestField}"/>
I have a property composed of email addresses of operators currently editing a record:
public ReactiveList<string> Operators { get; set; }
On the view side, I have a ListView of records, and for each of them an icon shows if the current user is an editing operator.
<FontIcon Glyph="" Visibility="{Binding Operators,
Converter={StaticResource IsUserEditingToVisibilityConverter} }" />
My problem is that the Convert() method of IsUserEditingToVisibilityConverter is not triggered when an update occurs in Operators. A TextBlock I set for debugging purpose does update though:
<TextBlock Text="{Binding Operators[0]}" />
Here's the code of IsUserEditingToVisibilityConverter:
// Taken from https://blogs.msdn.microsoft.com/mim/2013/03/11/tips-winrt-converter-parameter-binding/
public class IsUserEditingToVisibilityConverter : DependencyObject, IValueConverter
{
public UserVm CurrentUser
{
get { return (UserVm)GetValue(CurrentUserProperty); }
set { SetValue(CurrentUserProperty, value); }
}
public static readonly DependencyProperty CurrentUserProperty =
DependencyProperty.Register("CurrentUser",
typeof(UserVm),
typeof(IsUserEditingToVisibilityConverter),
new PropertyMetadata(null));
public object Convert(object value, Type targetType, object parameter, string language)
{
if (this.CurrentUser == null) return Visibility.Collapsed;
if (this.CurrentUser.EmailAddress == null) return Visibility.Collapsed;
var operators = value as IList<string>;
if (operators != null && operators.Contains(this.CurrentUser.EmailAddress))
{
return Visibility.Visible;
}
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
The binding to Text will only update here Operators changes - as in if you were to do something like:
Operators = new ReactiveList<string>{"first", "second"};
and Operators was declared as below (which ensures that PropertyChanged is raised):
public ReactiveList<string> Operators
{
get { return _operators; }
set { this.RaiseAndSetIfChanged(ref _operators, value); }
}
It will not update if you add items to or remove items from the list.
I think you're probably doing too much in a converter here - this behaviour would be better off in the View Model. You'd have a CurrentUser property, an Operators list, and declare property using ReactiveUI's ObservableAsPropertyHelper that would update when either CurrentUser or Operators changed:
private readonly ObservableAsPropertyHelper<bool> _isUserEditing;
public ReactiveList<string> Operators { get; } = new ReactiveList<string>();
public UserVm CurrentUser
{
get { return _currentUser; }
set { this.RaiseAndSetIfChanged(ref _currentUser, value); }
}
public bool IsUserEditing => _isUserEditing.Value;
And in the constructor:
Operators.Changed.Select(_ => Unit.Default)
.StartWith(Unit.Default)
.Select(_ => WhenCurrentUserEditing())
.Switch()
.ToProperty(this, x => x.IsUserEditing, out _isUserEditing);
With WhenCurrentUserEditing implemented as:
private IObservable<bool> WhenCurrentUserEditing()
{
return this.WhenAnyValue(x => x.CurrentUser.EmailAddress)
.Select(Operators.Contains);
}
I'm dealing with some WPF problems using and sticking to the MVVM pattern.
Most of my properties look like this:
public string Period
{
get { return _primaryModel.Period; }
set
{
if (_primaryModel.Period != value)
{
_primaryModel.Period = value;
RaisePropertyChanged("Period");
}
}
}
This works excellent.
However I also have some properties like this:
public bool EnableConsignor
{
get
{
return (ConsignorViewModel.Id != 0);
}
}
It doesn't have a setter as the id is changed "automatically" (every time the save of ConsignorViewModel is called. However this leads to the problem that the "system" doesn't know when the bool changes from false to true (as no RaisePropertyChanged is called).
For these kinds of properties, you need to just raise PropertyChanged when the dependent data is changed. Something like:
public object ConsignorViewModel
{
get { return consignorViewModel; }
set
{
consignorViewModel = value;
RaisePropertyChanged("ConsignorViewModel");
RaisePropertyChanged("EnableConsignor");
}
}
RaisePropertyChanged can be invoked in any method, so just put it after whatever operation that would change the return value of EnableConsignor is performed. The above was just an example.
I wrote this a while ago an it has been working great
[AttributeUsage(AttributeTargets.Property, Inherited = false)]
public class CalculatedProperty : Attribute
{
private string[] _props;
public CalculatedProperty(params string[] props)
{
this._props = props;
}
public string[] Properties
{
get
{
return _props;
}
}
}
The ViewModel base
public class ObservableObject : INotifyPropertyChanged
{
private static Dictionary<string, Dictionary<string, string[]>> calculatedPropertiesOfTypes = new Dictionary<string, Dictionary<string, string[]>>();
private readonly bool hasComputedProperties;
public ObservableObject()
{
Type t = GetType();
if (!calculatedPropertiesOfTypes.ContainsKey(t.FullName))
{
var props = t.GetProperties();
foreach (var pInfo in props)
{
var attr = pInfo.GetCustomAttribute<CalculatedProperty>(false);
if (attr == null)
continue;
if (!calculatedPropertiesOfTypes.ContainsKey(t.FullName))
{
calculatedPropertiesOfTypes[t.FullName] = new Dictionary<string, string[]>();
}
calculatedPropertiesOfTypes[t.FullName][pInfo.Name] = attr.Properties;
}
}
if (calculatedPropertiesOfTypes.ContainsKey(t.FullName))
hasComputedProperties = true;
}
public event PropertyChangedEventHandler PropertyChanged;
public virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
if (this.hasComputedProperties)
{
//check for any computed properties that depend on this property
var computedPropNames =
calculatedPropertiesOfTypes[this.GetType().FullName]
.Where(kvp => kvp.Value.Contains(propertyName))
.Select(kvp => kvp.Key);
if (computedPropNames != null)
if (!computedPropNames.Any())
return;
//raise property changed for every computed property that is dependant on the property we did just set
foreach (var computedPropName in computedPropNames)
{
//to avoid stackoverflow as a result of infinite recursion if a property depends on itself!
if (computedPropName == propertyName)
throw new InvalidOperationException("A property can't depend on itself");
OnPropertyChanged(computedPropName);
}
}
}
protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value))
return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
}
Example:
public class ViewModel : ObservableObject
{
private int _x;
public int X
{
get { return _x; }
set { SetField(ref _x, value); }
}
private int _y;
public int Y
{
get { return _y; }
set { SetField(ref _y, value); }
}
//use the CalculatedProperty annotation for properties that depend on other properties and pass it the prop names that it depends on
[CalculatedProperty("X", "Y")]
public int Z
{
get { return X * Y; }
}
[CalculatedProperty("Z")]
public int M
{
get { return Y * Z; }
}
}
Note that:
it uses reflection only once per type
SetField sets the field and raises property changed if there is a new value
you don't need to pass property name to SetField as long as you call it within a setter because the
[CallerMemberName] does it for you since c# 5.0.
if you call SetField outside the setter then you will have to pass
it the property name
as per my last update you can avoid using SetField by setting the field directly and then
calling OnPropertyChanged("PropertyName") and it will raise
PropertyChanged for all properties that are
dependant on it.
in c# 6 you can use the nameof operator to get the property name such
as nameof(Property)
OnPropertyChanged will call itself recusively if there are computed
properties
XAML for testing
<StackPanel>
<TextBox Text="{Binding X,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBox>
<TextBox Text="{Binding Y,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBox>
<TextBlock Text="{Binding Z,Mode=OneWay}"></TextBlock>
<TextBlock Text="{Binding M,Mode=OneWay}"></TextBlock>
</StackPanel>