Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

mvvm - Silverlight 4: how to switch control visibility

I am using MVVM in my Silverlight app. When control visibility is need to be managed by data, I am connecting its 'Visibility' property to object's corresponding property:

XAML:

<TextBlock Text="Price" Visibility="{Binding PriceVisibility, Mode=OneWay}"/>
<TextBox Text="{Binding TicketPrice, Mode=TwoWay}" Visibility="{Binding PriceVisibility, Mode=OneWay}"/>

CodeBehind (C#):

public string PriceVisibility { get { return PriceVisible ? "Visible" : "Collapsed"; } }

But from my perspective, returning string representation of the Visibility property is not a best approach.

Could you please advise if there are any better way?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I just used Reflector to inspect the type converters in the PresentationFramework.dll

There is already an implementation that can convert between boolean and visibility. You should be able to make use of this in your silverlight application.

public sealed class BooleanToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool flag = false;
        if (value is bool)
        {
            flag = (bool) value;
        }
        else if (value is bool?)
        {
            bool? nullable = (bool?) value;
            flag = nullable.HasValue ? nullable.Value : false;
        }
        return (flag ? Visibility.Visible : Visibility.Collapsed);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((value is Visibility) && (((Visibility) value) == Visibility.Visible));
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...