MVVM - binding to check box if checkbox checked
data-binding, mvvm
Solution
Here is one MVVM type of approach that assumes you understand INotifyPropertyChanged (you need to!). Play with it and feel free to ask about anything you get stuck on.
VM (viewmodel code)
public class MyViewModel : INotifyPropertyChanged {
const string Msg1 = "blah 1";
const string Msg2 = "blah 2";
private bool _isSelected;
public bool IsSelected{
get { return _isSelected; }
set {
if(_isSelected == value) return;
_isSelected = value;
MyBoundMessage = _isSelected ? Msg1 : Msg2;
NotifyPropertyChanged(()=> IsSelected);
NotifyPropertyChanged(()=> MyBoundMessage);
}
}
public string MyBoundMessage {get;set;}
}
V (view XAML)
<CheckBox IsChecked="{Binding IsSelected}" />
<TextBox Text="{Binding MyBoundMessage}" />
Problem
I want to bind a string value to a text box but only if a check box is checked. So, if the checkbox is checked I want the textbox to display Message 1, if not then display Message 2. What is the best way to do this? Is it better to use a List property in my object and then depending on if the check box is checked or not depends on which item from within my List<> is displayed or is it better to just update the object's property (this time of type string) after the checkbox is selected and then re-bind?