本文介绍了Silverlight 4:如何切换控件可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Silverlight 应用程序中使用 MVVM.当需要通过数据管理控件可见性时,我将其可见性"属性连接到对象的相应属性:

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}"/>

代码隐藏(C#):

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

但从我的角度来看,返回 Visibility 属性的字符串表示并不是最好的方法.

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?

谢谢!

推荐答案

我刚刚使用 Reflector 检查 PresentationFramework.dll 中的类型转换器

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

已经有一个实现可以在布尔值和可见性之间进行转换.您应该可以在您的 Silverlight 应用程序中使用它.

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));
    }
}

这篇关于Silverlight 4:如何切换控件可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 08:38