Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Property Data binding to negate the property

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

like image 467
azamsharp Avatar asked Apr 05 '10 19:04

azamsharp


People also ask

How does data binding work in WPF?

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.

What is OneWayToSource data binding in WPF?

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.

Which class is used for data binding in WPF?

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.


1 Answers

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.

like image 60
Reed Copsey Avatar answered Oct 27 '22 01:10

Reed Copsey