user60333
user60333

Reputation: 123

Set element visibility by model value

I want to set the visibility of TextBox-elements based on their bindings.
Example: TextBoxes with price values for two products

<TextBox Grid.Column="1" Grid.Row="3" Text="{Binding PriceProduct0, Mode=TwoWay}" />
<TextBox Grid.Column="2" Grid.Row="3" Text="{Binding PriceProduct1, Mode=TwoWay}" />

In my model, I query the necessary values from a WCF service and call NotifyPropertyChanged to update my view.
The problem: in some scenarios, there are no values for my properties. In that case I want to hide the UI element. Is there an easy way, maybe by raising an event?

Most of the properties are double or boolean, so I can't set them NULL.

Solution:
I found a solution, thanks to Ahmed and DHN!
Here all steps:

  1. Change all non-nullable properties to nullables, e.g. public double? PriceProduct0
  2. Add a reference to the following .dll, if you can't find the namespace Microsoft.TeamFoundation.Controls.WPF.Converters:
    <VSHome>\Common7\IDE\PrivateAssemblies\Microsoft.TeamFoundation.Controls.dll
  3. Add xmlns:myConverters="clr-namespace:Microsoft.TeamFoundation.Controls.WPF.Converters;assembly=Microsoft.TeamFoundation.Controls" to the <Page> attribute
  4. Add <Page.Resources>
    <myConverters:NullToVisibleConverter x:Key="NullToVisibleConverter" />
    </Page.Resources>
  5. Add the following visibility parameter to the <TextBox> attribute:
    Visibility="{Binding PriceProduct0, Converter={StaticResource NullToVisibleConverter}, ConverterParameter='invert' }"

Upvotes: 0

Views: 362

Answers (2)

Mohd Ahmed
Mohd Ahmed

Reputation: 1482

You can use null to visibility converter. See this link

<TextBox Text="{Binding PriceProduct0}" Visibility="{Binding PriceProduct0, Mode=TwoWay, Converter={StaticResource NullToVisibilityConverter}}"/>

Upvotes: 4

DHN
DHN

Reputation: 4865

Nothing easier as this. Just a NullToVisibleConverter and bind it to the Visibility property of the UI element. E.g.

<Window>
    <Window.Resources>
        <NullToVisibleConverter x:Key="Null2VisConv"/>
    </Window.Resources>
<TextBox Visibility="{Binding PriceProduct0, Converter={StaticResource Null2VisConv}}" .../>
</Window>

Upvotes: 1

Related Questions