简体   繁体   中英

Conditional element in xaml depending on the binding content

Is it possible to display this TextBlock, only if the Address.Length > 0 ? I'd like to do this directly into the xaml, I know I could put all my controls programmatically

 <TextBlock Text="{Binding Path=Address}" />

Basically, you're going to need to write an IValueConverter so that you can bind the Visibility property of your TextBox to either the Address field, or a new field that you create.

If you bind to the Address field, here's how the binding might look like::

<TextBlock Text="{Binding Path=Address}"
    Visibility="{Binding Path=Address, Converter={StaticResource StringLengthVisibilityConverter}}" />

And then StringLengthVisiblityConverter could look something like this:

public class StringLengthVisiblityConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null || value.ToString().Length == 0)
        {
            return Visibility.Collapsed;
        }
        else
        {
            return Visibility.Visible;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Don't need to implement this
    }
}

Then you'd just need to add your converter as a resource, using syntax like this (where src is mapped to the namespace where the converter is defined):

<src:StringLengthVisiblityConverter x:Key="StringLengthVisiblityConverter" />

I would do this with another boolean property called HasAddress which returns Address.Length > 0 .

<!-- In some resources section -->
<BooleanToVisibilityConverter x:Key="Bool2VisibilityConverter" />

<TextBlock 
  Text="{Binding Address}" 
  Visibility="{Binding HasAddress, Converter={StaticResource Bool2VisibilityConverter}}" 
/>

You should also remember to notify the property change for HasAddress in the setter of Address .

You can create a StringToVisibility converter.

It will return Visibility.Visible if bound string is not null or empty and Visibility.Collapsed if it is.

Use this converter while binding Address with Visibility property of your TextBlock .

Example:

<TextBlock Text="{Binding Path=Address}" Visibility="{Binding Address, Converter={StaticResource StringToVisibilityConverter}}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM