Why does bool work for visibility without a converter when using traditional binding
Asked Answered
S

1

6

I have created and used bool to visibility converters before and the other day, I forgot to use a converter on the binding (I am using traditional binding). I bound the visibility property of the control in my view to a bool property in my view model and surprisingly it works. So my question is if it works with traditional binding, why do we need to use converters? Because it seems the compiler is doing the conversion for me.

I tested it on a UWP app in Visual studio Update 3. The minimum app target is 10.0.10586 The target version is 10.0.14393

Stringhalt answered 27/12, 2016 at 14:58 Comment(3)
Where did you get the idea you had to use a converter?Spermatophyte
@EBrown I have just always assumed and I have seen people use it in code samples, I guess I was mistaken.Stringhalt
It's unnecessary if the data doesn't need converted. In the case of something like a bool, the only time you would want to use it is if the bool value is an inverse of the desired intention.Spermatophyte
W
8

Interesting. This has always been a pain and it seems to have been fixed without much publicity, I didn't know this.

In WPF you always had to use a ValueConverter, because Visibility isn't a bool.

I just removed a BooleanToVisibility conversion from a {x:Bind ...} in my project and indeed it still works. I dug this up from the generated code:

private void Update_ViewModel_ShowMessage(global::System.Boolean obj, int phase)            
{
  ...
  this.Update_ViewModel_ShowMessage_Cast_ShowMessage_To_Visibility(
    obj ? global::Windows.UI.Xaml.Visibility.Visible 
        : global::Windows.UI.Xaml.Visibility.Collapsed
   , phase);
...
}

So apparently it is now built in.

Update:

For {x:Bind } it was announced here, as part of the anniversary update. And you do need to target 14393 or later. For older builds it only works in {Binding ...}.

Weatherspoon answered 28/12, 2016 at 8:16 Comment(5)
I guess if you want 'Hidden' instead of 'Collapsed' you will still need to use a converter.Jump
In UWP, Hidden does not exist anymore... Visibility is an enum with 2 members.Weatherspoon
Ah, and that frees the way for the automatic conversion.Jump
Does this work with the full desktop version of WPF too?Gag
@ScottChamberlain - haven't tried that yet but I don't think so.Weatherspoon

© 2022 - 2024 — McMap. All rights reserved.