I have a tab control on a page; its items are bound back to my ViewModel, which also exposes an ActiveTabItemIndex which is bound (two way) to the SelectedIndex property in my xaml, and which implements INotifyPropertyChanged so that my TabControl knows when to update.
This is (I understand) the MVVM-correct way to do things, and works 99% properly.
class MainWindowViewModel : BaseViewModel, INotifyPropertyChanged
{
ObservableCollection<TabItemViewModel> _TabItems;
int _ActiveTabItemIndex;
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(name));
}
void _TabItems_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
_ActiveTabItemIndex = _TabItems.IndexOf((TabItemViewModel)e.NewItems[0]);
RaisePropertyChanged("ActiveTabItemIndex");
}
public ObservableCollection<TabItemViewModel> TabItems
{
get
{
if (_TabItems == null)
{
_TabItems = new ObservableCollection<TabItemViewModel>();
_TabItems.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_TabItems_CollectionChanged);
}
return _TabItems;
}
}
public int ActiveTabItemIndex
{
get
{
return _ActiveTabItemIndex;
}
set
{
_ActiveTabItemIndex = value;
}
}
}
This way any manipulations I make to my TabItems collection are reflected on the TabControl, and when I add a new item, it is automatically selected. This works a treat; however, when adding the very first item to an empty tab control, it looks like this:
The tab contents are displayed, but the tab is not selected. I need to manually click the tab to get it to look right:
It is as though there is some kind of disconnect between the drawing of the tabs and the drawing of their contents. I know the binding is working because subsequent tabs are handled correctly and if I remove the binding altogether then the first page does not show its contents until the tab is manually selected. If anyone has seen this or can shed some light it would be very much appreciated! Thank you all :)
Only raise your property change events in the setter; you can think of it as allowing the property itself to dictate what "changed" means, and by extension, giving it control over when the event is fired (and makes it do what you expect):
public int ActiveTabItemIndex
{
get{ return _ActiveTabItemIndex; }
set
{
if(_ActiveTabItemIndex != value)
{
_ActiveTabItemIndex = value;
RaisePropertyChanged("ActiveTabItemIndex");
}
}
}
Just change
_ActiveTabItemIndex = _TabItems.IndexOf(...);
to
ActiveTabItemIndex = _TabItems.IndexOf(...);
and remove the RaisePropertyChanged call from _TabItems_CollectionChanged
There will be times when you'll need raise property changed notifications outside a property's setter but that is for a far more complicated day :)
As an aside, INotifyPropertyChanged should be implemented on your BaseViewModel. Check out the absolutely fantastic MVVM Light Toolkit - it has all the code you'd otherwise have to duplicate in every project that you use MVVM in.
Related
I have an ObservableCollection that populates a datagrid in WPF. I need to bind to the total of the "Hours" column, and have that total update when a value in the "Hours" column is changed. I can achieve this by listening to the "LostFocus" event and running a function, but would like to try my hand at binding.
The issue I am running into, is the NotifyPropertyChanged event will not fire when an items property in the collection is changed.
The sortie class NotifyPropertyChanged will fire, but the collection doesn't interpret that as its own property changing. How can I listen to the sortie PropertyChanged from the collection in the missions class?
My Models
public class Mission : INotifyPropertyChanged
{
private ObservableCollection<Sortie> sorties;
public ObservableCollection<Sortie> Sorties
{
get { return this.sorties; }
set
{
if (this.sorties != value)
{
this.sorties = value;
this.NotifyPropertyChanged("Sorties");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}
public class Sortie : INotifyPropertyChanged
{
private double hours;
public double Hours
{
get {return this.hours;}
set
{
if (this.hours != value)
{
this.hours = value;
this.NotifyPropertyChanged("Hours");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}
I didn't bother posting my XAML or View Model, as I am confident I can solve the issue once I learn how to trigger a PropertyChanged event for the collection and I wanted to spare you having to read through massive amounts of code. If you believe it is needed however, let me know.
Write a readonly property in the parent viewmodel that calculates the value.
public double SortieHours => Sorties.Sum(x => x.Hours);
Parent viewmodel handles PropertyChanged on each item in Sorties, and CollectionChanged on Sorties. In CollectionChanged on Sorties, you have to add/remove PropertyChanged handlers from Sortie instances as they're added and removed. When you get a new Sorties collection (you might want to make that setter private for this reason), you need to toss out all the old handlers and add new ones.
Now, whenever a Sortie is added or removed, or its Hours changes, or somebody hands you a new Sorties collection, raise PropertyChanged:
OnPropertyChanged(nameof(SortieHours));
And bind that property to whatever you like in the XAML.
This looks horrible (because it is), but what else are you going to do?
A lot of people would advise you to give Sortie an HoursChanged event. PropertyChanged is annoying for this type of case because it can get raised for multiple different properties and you have to check which one. And it's a magic string thing.
Above is C#6. For C#5,
public double SortieHours { get { return Sorties.Sum(x => x.Hours); } }
OnPropertyChanged("SortieHours");
I found this link to be a big help. It creates a base class for ObservableCollections to "AutoMagicly" add the PropertyChanged events of the collection items to the CollectionChanged event.
so I have a model which contains 2 variables, a List and a DateTime. In my UserControl I have a DependencyProperty and I also defined a PropertyChangedCallback.
public static readonly DependencyProperty MyProperty = DependencyProperty.Register("My", typeof(List<MyContainer>), typeof(UC), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(OnMyProperty)));
public List<MyContainer> My
{
get
{
return GetValue(MyProperty) as List<MyContainer>;
}
set
{
SetValue(MyProperty, value);
}
}
private static void OnMyProperty(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
UC control = d as UC;
//do stuff
}
On my form there is a button, which do the changes on the other model variable (on the DateTime).
private void Date_Click(object sender, RoutedEventArgs e)
{
MyModel model = DataContext as MyModel;
if (model != null)
{
model.Date = model.Date.AddDays(1);
}
}
And finally here is my model.
public class MyModel : INotifyPropertyChanged
{
private List<MyContainer> _My;
private DateTime _Date;
public MyModel()
{
_Date = DateTime.Now.Date;
_My = new List<MyContainer>();
}
public List<MyContainer> My
{
get
{
return _My;
}
set
{
_My = value;
OnPropertyChanged("My");
}
}
public DateTime Date
{
get
{
return _Date;
}
set
{
_Date = value;
OnPropertyChanged("Date");
OnPropertyChanged("My");
}
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
XAML declaration is the following.
<local:UC My="{Binding My}" />
So my problem is the after I hit the run, it fires the OnMyProperty once, after that if I hit the button, it changes the DateTime property well, but the OnMyProperty callback doesn't firing again. However I noticed that if I modify my model like this
public DateTime Date
{
get
{
return _Date;
}
set
{
_Date = value;
_My = new List<MyContainer>(_My); //added
OnPropertyChanged("Date");
OnPropertyChanged("My");
}
}
now it fires it every time when I hit the button. How can I trigger the second behaviour without that modification?
After setting the value of a DependencyProperty it first checks if the new value is different to the old one. Only in this case the PropertyChangedCallback method you registered with that DependencyProperty is called. So the name PropertyChanged makes sense.
In your (not modified) case you not even try to change My (only Date). So there is no reason to raise the callback function.
The answer is that you almost certainly do not need to do this. When you ask a question about how to make the framework do something it really does not want to do, always say why you think you need to do that. It's very likely that there's a much easier answer that everybody else is already using.
The only thing you have bound to the control is My. Therefore, if My hasn't changed, then the state of the control should not change. If you want the state of the control to change when Date changes, bind Date to some property of the control. The only way the control should ever get information from any viewmodel is through binding one of its dependency properties to a property of the viewmodel.
The control should not ever know or care who or what is providing values for its properties. It should be able to do its job knowing only the property values it has been given.
If the contents of My have changed -- you added an item or removed one -- of course the control has no way of knowing that, because you refused to tell it. You're just telling it there's a new list. It checks, sees it's still got the same old list, and ignores you. The My property of your viewmodel should be an ObservableCollection, because that will notify the control when you add or remove items in the collection.
The items themselves, your MyContainer class, must implement INofityPropertyChanged as well, if you want to be able to change their properties while they are displayed in the UI.
The dependency property My on your control must not be of type List<T>. It should probably be type object, just like ItemsControl.ItemsSource. Then your control template can display it in an ItemsControl which knows what to do with it. If an ObservableCollection is bound to it as I suggested above, the ItemsControl will update automatically. In OnMyProperty, your control class can check to see if it's an observable collection as well:
private static void OnMyProperty(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
UC control = d as UC;
if (e.NewValue is INotifyCollectionChanged)
{
(e.NewValue as INotifyCollectionChanged).CollectionChanged +=
(s, ecc) => {
// Do stuff with UC and ecc.NewItems, ecc.OldItems, etc.
};
}
}
Considering WPF controls, how do I know if a check box's value has changed (toggled)?
I know there are the common Checked, Unchecked, Clicked events, but how about an event for when the value changes, regardless of how it was changed?
I looked through the events and I didn't find anything, but maybe I'm missing the obvious (as it has happened many times in the past).
You can just bind IsChecked Dependency Property to a boolean. On that binded property setter you can manipulate what you want (independently if it's setting it to true or false). That works just as expected.
On your view:
<Grid>
<CheckBox ... IsChecked="{Binding ShowPending}"/>
</Grid>
On your DataContext ViewModel or CodeBehind.
private bool showPending = false;
public bool ShowPending
{
get { return this.showPending; }
set
{
//Here you mimic your Toggled event calling what you want!
this.showPending = value;
}
}
I know this already has an accepted answer, but binding is a bit overkill on this.
Just write one event handler and wire it to both the Checked and Unchecked events then check the IsChecked property inside your event handler.
Going off Randolf's answer, just create a class representing your window.
In the new class, create a property called BlahIsChecked. Implement the INotifyPropertChangedEvent in the class and in the setter of the the new property, fire the event with the property name.
class Blah : INotifyPropertyChanged
{
// Used for triggering the event
public event PropertyChangedEventHandler PropertyChanged;
// Called when the property changes
protected void OnPropertyChanged(String propertyName)
{
// Retrieve handler
PropertyChangedEventHandler handler = this.PropertyChanged;
// Check to make sure handler is not null
if(handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
private bool _blahIsChecked;
public bool BlahIsChecked
{
get {
return _blahIsChecked;
}
set {
_blahIsChecked = value;
OnPropertyChanged("BlahIsChecked);
}
}
}
Now, go to your wpf class and say this.DataContext = new MainModel(); You can do this in WPF or c#.
Now in your checkbox xaml do the following
<checkbox Checked="{Binding BlahIsChecked, Mode=TwoWay}"/>
I did this from memory but should get you started. Good luck.
Your best option is probably the IsChecked property. But if you require an event, you can look at creating a DependencyPropertyDescriptor and registering a handler with the AddValueChanged method.
I think this is about as close as you'll get to an evented notification that the check box's value has changed. Creating the descriptor and adding the handler looks something like this:
var dpd = DependencyPropertyDescriptor.FromProperty(CheckBox.IsChecked, typeof(CheckBox));
dpd.AddValueChanged(...);
I have a simple usercontrol (WinForms) with some public properties. When I use this control, I want to databind to those properties with the DataSourceUpdateMode set to OnPropertyChanged. The datasource is a class which implements INotifyPropertyChanged.
I'm aware of the need to create bindings against the properties and I'm doing that.
I assumed that my usercontrol would have to implement an interface, or the properties would need to be decorated with some attribute, or something along those lines.But my research has come up blank.
How should this be accomplished? At the moment I'm doing it by calling OnValidating() in my usercontrol whenever a property changes, but that doesn't seem right.
I can get validation to happen if I set the CausesValidation to true on the usercontrol, but that's not very useful to me. I need to validate each child property as it changes.
Note this is a WinForms situation.
EDIT: Evidently I have no talent for explanation so hopefully this will clarify what I'm doing. This is an abbreviated example:
// I have a user control
public class MyControl : UserControl
{
// I'm binding to this property
public string ControlProperty { get; set; }
public void DoSomething()
{
// when the property value changes, the change should immediately be applied
// to the bound datasource
ControlProperty = "new value";
// This is how I make it work, but it seems wrong
OnValidating();
}
}
// the class being bound to the usercontrol
public class MyDataSource : INotifyPropertyChanged
{
private string sourceProperty;
public string SourceProperty
{
get { return sourceProperty; }
set
{
if (value != sourceProperty)
{
sourceProperty = value;
NotifyPropertyChanged("SourceProperty");
}
}
}
// boilerplate stuff
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
public class MyForm : Form
{
private MyControl myControl;
public MyForm()
{
// create the datasource
var dataSource = new MyDataSource() { SourceProperty = "test" };
// bind a property of the datasource to a property of the usercontrol
myControl.DataBindings.Add("ControlProperty", dataSource, "SourceProperty",
false, DataSourceUpdateMode.OnPropertyChanged); // note the update mode
}
}
(I have tried this using a BindingSource, but the result was the same.)
Now what I want to happen is that when the value of MyControl.ControlProperty changes, the change is immediately propagated to the datasource (the MyDataSource instance). To achieve this I call OnValidating() in the usercontrol after changing the property. If I don't do that, I have to wait until validation gets triggered by a focus change, which is the equivalent of the "OnValidation" update mode, rather than the desired "OnPropertyUpdate" validation mode. I just don't feel like calling OnValidating() after altering a property value is the right thing to do, even if it (kind of) works.
Am I right in assuming the calling OnValidating() is not the right way to do this? If so, how do I notify the datasource of the ControlProperty change?
I think I've got this figured out. I didn't understand how change notifications were sent from control to bound datasource.
Yes, calling OnValidating() is the wrong way.
From what I've pieced together, there are two ways a control can notify the datasource that a property has changed.
One way is for the control to implement INotifyPropertyChanged. I had never done this from the control side before, and I thought only the datasource side of the binding had to implement it.
When I implemented INotifyPropertyChanged on my user control, and raised the PropertyChanged event at the appropriate time, it worked.
The second way is for the control to raise a specific change event for each property. The event must follow the naming convention: <propertyname>Changed
e.g. for my example it would be
public event EventHandler ControlPropertyChanged
If my property was called Foo, it would be FooChanged.
I failed to notice the relavent part of the MSDN documentation, where it says:
For change notification to occur in a
binding between a bound client and a
data source, your bound type should
either:
Implement the INotifyPropertyChanged
interface (preferred).
Provide a change event for each
property of the bound type.
This second way is how all existing WinForms controls work, so this is how I'm doing it now. I use INotifyPropertyChanged on my datasource, but I raise the Changed events on my control. This seems to be the conventional way.
Implementing the INotifyPropertyChanged interface is very simple. Here is a sample that shows an object with a single public field...
public class Demo : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
private string _demoField;
public string DemoField
{
get {return demoField; }
set
{
if (value != demoField)
{
demoField = value;
NotifyPropertyChanged("DemoField");
}
}
}
}
Then you would create a Binding instance to bind a control property to a property (DemoField) on your source instance (instance of Demo).
In WPF, I have a ListView bound to an ObservableCollection in the code-behind. I have working code that adds and removes items from the list by updating the collection.
I have an 'Edit' button which opens a dialog and allows the user to edit the values for the selected ListView item. However, when I change the item, the list view is not updated. I'm assuming this is because I'm not actually adding/removing items from the collection but just modifying one of its items.
How do I tell the list view that it needs to synchronize the binding source?
You need to implement INotifyPropertyChanged on the item class, like so:
class ItemClass : INotifyPropertyChanged
{
public int BoundValue
{
get { return m_BoundValue; }
set
{
if (m_BoundValue != value)
{
m_BoundValue = value;
OnPropertyChanged("BoundValue")
}
}
}
void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
int m_BoundValue;
}
Do you have set the binding mode to TwoWay? If not, try to do that.