Is there any way to change the value of property at runtime in WPF data binding. Let's say my TextBox is bind to a IsAdmin property. Is there anyway I can change that property value in XAML to be !IsAdmin.
I just want to negate the property so Valueconverter might be an overkill!
NOTE: Without using ValueConverter
Data binding is a mechanism in WPF applications that provides a simple and easy way for Windows Runtime apps to display and interact with data. In this mechanism, the management of data is entirely separated from the way data. Data binding allows the flow of data between UI elements and data object on user interface.
OneWayToSource: The Source property will change if the target property is changed. If the user changes the TextProperty , the UserName property will take up the changed value. This again is of intermediate cost as the binding system watches only Target for changes.
WPF data binding supports data in the form of CLR objects and XML. To provide some examples, your binding source may be a UIElement, any list object, a CLR object that is associated with ADO.NET data or Web Services, or an XmlNode that contains your XML data.
You can use an IValueConverter
.
[ValueConversion(typeof(bool), typeof(bool))] public class InvertBooleanConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { bool original = (bool)value; return !original; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { bool original = (bool)value; return !original; } }
Then you'd setup your binding like:
<TextBlock Text="{Binding Path=IsAdmin, Converter={StaticResource boolConvert}}" />
Add a resource (usually in your UserControl/Window) like so:
<local:InvertBooleanConverter x:Key="boolConvert"/>
Edit in response to comment:
If you want to avoid a value converter for some reason (although I feel that it's the most appropriate place), you can do the conversion directly in your ViewModel. Just add a property like:
public bool IsRegularUser { get { return !this.IsAdmin; } }
If you do this, however, make sure your IsAdmin
property setter also raises a PropertyChanged
event for "IsRegularUser" as well as "IsAdmin", so the UI updates accordingly.
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