Reputation: 5576
I have a datagrid with a variable number of columns that I am generating programatically. It contains DataGridTemplateColumns, each with a DockPanel containing a CheckBox and a TextBlock.
Binding code:
Binding bindingPicked = new Binding(string.Format("Prices[{0}].Picked", i));
bindingPicked.Mode = BindingMode.TwoWay;
CheckBox code:
FrameworkElementFactory factoryCheckBox = new FrameworkElementFactory(typeof(CheckBox));
factoryCheckBox.SetValue(CheckBox.IsCheckedProperty, bindingPicked);
Picked property:
private bool _picked;
public bool Picked
{
get { return _picked; }
set { _picked = value; }
}
When the datagrid is initialized, the Picked getters are called as expected. However, when I check/uncheck a checkbox, the setter isn't called. What is causing this? I do not want to use a DependencyProperty, and I don't think it should be needed as I just need the property setter to be called when the user clicks the CheckBox.
EDIT: Apparently I am a moron, I simply forgot bindingPicked.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; Feel free to close this.
Upvotes: 2
Views: 3688
Reputation: 770
As above, you need to implement INotifyPropertyChanged The correct pattern to follow is:
private bool _picked;
public bool Picked
{
get { return _picked; }
set
{
if (_picked != value)
{
_picked = value;
if (null != PropertyChanged)
{
PropertyChanged(this, new PropertyChangedEventArgs("Picked"));
}
}
}
}
The UpdateSourceTrigger property tells databinding when to update the source. For example, with a TextBox, the default is LostFocus. For most other controls it is PropertyChanged.
Upvotes: 0
Reputation: 194
I Think you should Implement INotifyPropertyChanged's and call the event in set
Upvotes: 1
Reputation: 27115
bindingPicked.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
That should do it :)
Upvotes: 5