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?
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.
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}" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With