Someone please help. I have an interesting issue. I am trying to implement an MVVM app and I want to bind to radiobuttons in my view.
Here's my view:
<StackPanel Orientation="Horizontal" Grid.ColumnSpan="2" >
<RadioButton GroupName="1" IsChecked="{Binding Path=NoteGeneral, Mode=TwoWay}">General</RadioButton>
<RadioButton GroupName="1" IsChecked="{Binding Path=NoteContact, Mode=TwoWay}" >Contact</RadioButton>
<RadioButton GroupName="1" IsChecked="{Binding Path=NoteAddress, Mode=TwoWay}" >Address</RadioButton>
<RadioButton GroupName="1" IsChecked="{Binding Path=NotePhone, Mode=TwoWay}" >Phone</RadioButton>
</StackPanel>
Here's my ViewModel:
bool _NoteGeneral;
public bool NoteGeneral
{
get { return _NoteGeneral; }
set
{
_NoteGeneral = value;
OnPropertyChanged("NoteGeneral");
}
}
bool _NoteContact;
public bool NoteContact
{
get { return _NoteContact; }
set
{
_NoteContact = value;
OnPropertyChanged("NoteContact");
}
}
bool _NoteAddress;
public bool NoteAddress
{
get { return _NoteAddress; }
set
{
_NoteAddress = value;
OnPropertyChanged("NoteAddress");
}
}
bool _NotePhone;
public bool NotePhone
{
get { return _NotePhone; }
set
{
_NotePhone = value;
OnPropertyChanged("NotePhone");
}
}
The problem is this, when I click the different radiobuttons the property setter only gets called the first time(when i run thru debugging). e.g. When I click NoteGeneral, NoteContact, then NoteGeneral again only the first two clicks update my viewmodel. I think I might have something wrong with my binding, or maybe I'm approaching this the completely wrong way.
Can anyone help?
How should I implement radiobutton selections in my viewmodel?
.NET 4 and Later
This issue with RadioButton binding was resolved by Microsoft when .NET 4 was released. Binding of RadioButtons now works as you would expect without any of the work-arounds listed below.
Jaime Rodriguez, who works at Microsoft on WPF, publishes an unabridged Q&A on WPF, and the latest issue has a post on RadioButtons and MVVM !
The post is at http://blogs.msdn.com/jaimer/archive/2009/09/22/wpf-discussion-090922.aspx, and you want to look at the last item in that post. I tested the solution and it works to my satisfaction.
Quoted for convenience:
Take a look here.
I haven't implemented the solution provided but it makes sense. The underlying framework control breaks you bindings when a click is performed. The solution is to override the method that does this and just rely on the bindings.
I've written a simple tip for this problem on my blog.
In this case, you should write the View and the ViewModel as the following:
you have to set UpdateSourceTrigger="PropertyChanged" at XAML binding like