C# 如何使用默认值为visible的BooleanToVisibilityConverter?
此代码运行良好,但按钮可见性在设计中被折叠 如何将其设置为可见C# 如何使用默认值为visible的BooleanToVisibilityConverter?,c#,xaml,binding,visibility,C#,Xaml,Binding,Visibility,此代码运行良好,但按钮可见性在设计中被折叠 如何将其设置为可见 <!--Resources--> <BooleanToVisibilityConverter x:Key="BoolToVis" /> <Button Visibility="{Binding Converter={StaticResource BoolToVis}, Source={x:Static local:ConfigUser.Prc}}" Grid.Row="1"/> 如果我得到
<!--Resources-->
<BooleanToVisibilityConverter x:Key="BoolToVis" />
<Button Visibility="{Binding Converter={StaticResource BoolToVis}, Source={x:Static local:ConfigUser.Prc}}" Grid.Row="1"/>
如果我得到了你想要的。您需要的是在设计模式下显示该按钮,以及在运行时将布尔值设置为true时显示该按钮 如果转换器处于设计模式,除布尔值外,还可以创建用于测试的转换器:
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
public class DesignVisibilityConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
if (value is bool) {
return ((bool) value) || DesignerProperties.GetIsInDesignMode(Application.Current.MainWindow)
? Visibility.Visible
: Visibility.Collapsed;
}
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
throw new NotImplementedException();
}
}
这个默认为可见。这是我的逆布尔托维斯
[ValueConversion(typeof(bool), typeof(Visibility))]
public class InverseBooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (value != null && (bool)value) ?
Visibility.Collapsed : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return (value != null) && ((Visibility)value == Visibility.Collapsed);
}
}
下面是另一个问题的答案:这是因为Bool的默认值为false。可能是,如果不影响任何逻辑,您可以将初始值设置为true。您是否尝试将
FallbackValue设置为true?谢谢,@nkonishvt,但当我使用(cm:DesignerProperties.IsInDesignMode)时运行时可见性不会改变。Joseph我尝试将true设置为初始值,但没有成功。MikeEason我尝试使用FallbackValue=true,但在设计模式下不起作用:(DesignerProperties.GetIsInDesignMode(Application.Current.MainWindow)
在不使用主窗口时可能会失败。请将其替换为DesignerProperties.GetIsInDesignMode(new DependencyObject())
而且它很有魅力。尽管如此,我还是非常喜欢你的实现。@ChristianIvicevic好建议。谢谢!你的更好。