WinForms - how to set property value in code and get bound control to update? - winforms

I have a WinForms app that contains several comboboxes, numericupdown controls and checkboxes. I also have a data class that exposes several properties and these controls are bound to those properties. Now I need the ability to restore the default values for each of these properties and have all of the bound controls update to reflect the change. For example, one of my comboBox controls is bound to an enum that contains (Red, Blue, Yellow and Green). The default value for this property is set to Blue in my data class constructor. When my app starts up, the combobox that's bound to this property correctly displays Blue as the default selected item. If a user were to select a different color and then decide that they want to revert back to the default color, I need a way to change the property value back to Blue and get the bound control to show that. I can set the property value in code but the problem is that my comboBox doesn't update to reflect the change. I'm guessing there's some kind of change notification mechanism that I need to implement in my data class but I'm not sure what that would be. Any ideas would be much appreciated. Thanks very much!

You'll need to implement INotifyProperyChanged in your data class like:
public class Coloring : INotifyPropertyChanged
{
private string _name;
public string Name
{
get { return _name; }
set
{
if (_name != value) {
_name = value;
OnPropertyChanged("Name");
}
}
}
// Do this for all your properties
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null) {
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}

If you are using a BindingSource you can call its ResetBindings method.
myBindingSource.ResetBindings(false);

Related

How to replace griddata content when another control's (e.g. combobox) selection is changed?

This is probably not that difficult but as a wpf/mvvm beginner I'm still struggling with some basics.
I have a combobox (acts like a filter) and a griddata in a view. I use MMVM and databinding. On startup griddata is populated and the combobox's selection is set - that works fine. I'd like to replace the content of the griddata when the selection in the combobox changes. The combobox selected value is bound to a property in my viewmodel so I know when it changes and I can easily replace the content of the collection (which is IList) bound to the griddata. However I do not know how to force the griddata to 'refresh' itself in the view using mvvm bindings.
I was considering using ObservableCollection<> but from what I've read it looks like replacing the content is not that simple either. I do not really need the view to know when a single item in the collection changes - I will always replace the whole content of the list.
I'd appreciate any suggestions.
You can implement INotifyPropertyChanged in you ViewModel and call it when the List changes.
Example:
public class ViewModel : INotifyPropertyChanged
{
private List<MyObject> _myList;
public List<MyObject> MyList
{
get { return _myList; }
set { _myList = value; NotifyPropertyChanged(); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged([CallerMemberName]string propertyName = null)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Now when you replace MyList e.g. MyList = newlist it will tell the UI to update whatever is bound to MyList

How can I get bindings to update when the value is changed?

I'm trying to understand WPF binding. As simple as it gets:
I have a ClassWithProperty that has a public uint Prop1.
The main window has a public ClassWithProp object and uses it for data context. This is set in the main Windows's constructor:
this.ClassWithProp = new ClassWithProp();
this.DataContext = this.ClassWithProp;
ClassWithProp's default constructor sets Porp1 value to 1.
The main windows contains a label:
<Label Content="{Binding Prop1}" ... />
It also contains a button that, when click, sets the ClassWithProp.Prop1 to 2.
When the window first appears, the label correctly shows 1. When the button is clicked the property's value is changed to 2, but the lable does not refresh.
Sorry - probably obvious but I'm a novice in WPF:
Why doesn't the bound label update when the undelying property changes?
Your ClassWithProperty needs to implement the INotifyPropertyChanged interface (which has just the one event on it, PropertyChanged), this way the WPF binding subsystem can listen for property changes and update the value. When you have changed the value of a property, you raise the event.
Here is an example:
pulic class ClassWithProperty : INotifyPropertyChanged
{
public uint Prop1
{
get { return _prop1; }
set
{
_prop1 = value;
OnPropertyChanged("Prop1");
}
}
protected void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
private uint _prop1;
}
Implement INPC.
Also read the overview, it probably answers more than 90% of questions people have about data binding.

Propagate changes in model to view in Silverlight

in my Silverlight 4 Application I have an ObservableCollection that I data bind to two different listboxes. The listboxitems showing the content of the MyClass-Object. When I add an item to the ObservableCollection, the new item is displayed in both listboxes properly.
I have set the Binding Mode to two way, so that editing the listboxitems will update the model automatically. This works so far. My problem is, that the content of the other listbox doesn't update with the updated model. Adding a new item will properly show up on the other listbox, but the updates of the content (which I checked happens) won't.
Any ideas how to achieve: The content of the other listbox should update automatically, when the I update the content in one listbox.
Thanks in advance,
Frank
To expand on what luke said your class needs to implement INotifyPropertyChanged and your properties need to throw the PropertyChanged event in their setters.
public class MyClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged; // This may be named wrong
private string _myString = null;
public string MyString
{
get { return _myString; }
set
{
if(value == _myString)
return;
_myString = value;
var eh = PropertyChanged;
if(eh != null)
eh(this, new PropertyChangedEventArgs("MyString"));
}
}
}
The MyString property will notify the UI that it has changed which will trigger the binding to update.
you need to make sure that your objects in the observable collection implement INotifyPropertyChanged and they should post change events when your content properties change.

how do i get a wpf window to refresh?

I am building a simple roulette app. The player(UI) puts together a list of bets and submits them to the table object to be evaluated and paid out. I've got the code to work and the game process goes smoothly. The problem is that after a turn I can't get the player balance(textblock) or the betlist(listview) to update. Is there some sort of global window refresh command I am missing, or do I have to manually set each of these to update somehow?
WPF can take care of updating these values for you automatically, but you have to let it know when things have changed. Typically, this is done by using DependencyProperties on your model objects, but it can also be done by implementing INotifyPropertyChanged. In either case, when you update a property's value, the PropertyChanged event gets called; WPF automatically subscribes to this event when it binds to a value, and will update the UI when a change occurs. Without this notification, WPF won't check to see if the values in your object have changed, and you won't see the change reflected on the screen.
What about implementing INotifyPropertyChanged, and bind the balance and the betlist to the controls you are using?
Something like:
public class Player : INotifyPropertyChanged
{
private int _balance;
#region Properties
public int Balance
{
get { return this._balance; }
set
{
if (this._balance != value)
{
this._balance = value;
NotifyPropertyChanged("Balance");
}
}
}
public BindingList<Bet> BetList { get; set; }
#endregion // Properties
private void NotifyPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
public class Bet
{
// some code
}
For the binding list you wouldn't need to implement anything since it implements an interface that notifies changes to whatever is bound to (IRaiseItemChangedEvents). But then again you could be using a different approach.

Can't get a DataGrid to update

I have a WPF Toolkit DataGrid bound to an ObservableCollection of Car in my view model. Car has a PropertyChanged event and the setters of each of its two string properties fire the event. I also have the grid's SelectedItem property bound to a property in the view model of type Car, also called SelectedItem.
On the same window as the grid, I have buttons for add, modify and delete. Add and modify open a dialog window with two textboxes, one for each Car property. Delete just shows a confirm dialog then does the delete.
For add and delete, I add or delete an item from the ObservableCollection and the grid updates itself as expected. However, for modify it does not. At first, my Car did not use PropertyChanged and after some searching I found that it needed to for the grid to update when an individual item's properties changed. But now that I am using PropertyChanged, the grid still doesn't update.
I've tried changing the values of the SelectedItem in my view model as well as directly changing the item on the collection.
What am I doing wrong?
Make sure you're implementing INotifyPropertyChanged and not just raising a PropertyChanged event. Also, when raising PropertyChanged, you must pass "this" as the sender, otherwise WPF will ignore the event.
Below is a simple base class that implements INotifyPropertyChanged.
public class Person : INotifyPropertyChanged {
private string name;
public string Name {
get { return name; }
set {
if (name != value) {
name = value;
OnPropertyChanged("Name");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName) {
var handler = PropertyChanged;
if (handler != null) {
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Sounds like the classic problem with ObservableCollection. ObservableCollection only notifies of additions, deletions, etc. on it's self. It will NOT notify of changes to properties of whatever you have stored in it. This is why your add/delete operations work as expected.
What you should do is use a CollectionView and bind to that:
ObservableCollection<MyObject> myCollection = new ObservableCollection<MyObject>();
ICollectionView view = CollectionViewSource.GetDefaultView(myCollection);
using this method also has the benifit that grouping and sorting are built into the view.

Resources