简体   繁体   中英

Change element property based on bound value

I need to change properties on an Image element based on values in the bound object.

I have an image element:

<Image Source="{Binding Thing.Url}" Stretch="UniformToFill" HorizontalAlignment="Left"/>

If Thing.OtherProperty = true , then I want to add HorizontalAlignment="Center" to the Image element.

Note, the Image element is in a DataTemplate which is used in various places in the app.

What's the best way to accomplish this?

This is where you would use a Binding Converter

In your case you want to change the HorizontalAlignment property based on a Boolean. You first need to write a class that implements IValueConverter where you will write your conversion logic:

public class AlignmentConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if ((bool)value)
            return Windows.UI.Xaml.HorizontalAlignment.Center;

        return Windows.UI.Xaml.HorizontalAlignment.Left;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

*you will probably need to handle the errors a bit better in case you ever bind this to a property that is not boolean

To use this you need to import your coverters namespace at the top of the page

xmlns:converters="using:*yournamespace*"

...declare the converter as a resource:

<converters:AlignmentConverter x:Key="HorizontalAlignmentConverter"/>

... and use it as a parameter in your binding

<Image Source="{Binding Thing.Url}" Stretch="UniformToFill" HorizontalAlignment="{Binding Thing.OtherProperty, Converter={StaticResource HorizontalAlignmentConverter}"/>

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