Jak odwrócić BooleanToVisibilityConverter?
Używam BooleanToVisibilityConverter
w WPF, aby powiązać właściwość Visibility
kontrolki z Boolean
. To działa dobrze, ale chciałbym, aby jedna z kontrolek ukryła, jeśli wartość logiczna jest true
, i pokazała, jeśli jest false
.
16 answers
Zaimplementuj własną implementację IValueConverter. Przykładowa implementacja znajduje się na
Http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx
W metodzie Convert zwróć żądane wartości zamiast wartości domyślnych.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-27 12:32:47
Zamiast odwracania, można osiągnąć ten sam cel, używając ogólnej implementacji IValueConverter
, która może konwertować wartość logiczną na wartość docelową konfigurowalną dla wartości true I false. Poniżej znajduje się jedna taka implementacja:
public class BooleanConverter<T> : IValueConverter
{
public BooleanConverter(T trueValue, T falseValue)
{
True = trueValue;
False = falseValue;
}
public T True { get; set; }
public T False { get; set; }
public virtual object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value is bool && ((bool) value) ? True : False;
}
public virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value is T && EqualityComparer<T>.Default.Equals((T) value, True);
}
}
Następnie podklasuj gdzie T
jest Visibility
:
public sealed class BooleanToVisibilityConverter : BooleanConverter<Visibility>
{
public BooleanToVisibilityConverter() :
base(Visibility.Visible, Visibility.Collapsed) {}
}
Wreszcie, możesz użyć BooleanToVisibilityConverter
powyżej w XAML i skonfigurować go tak, aby na przykład używać Collapsed
dla true i Visible
dla false:
<Application.Resources>
<app:BooleanToVisibilityConverter
x:Key="BooleanToVisibilityConverter"
True="Collapsed"
False="Visible" />
</Application.Resources>
Ta inwersja jest przydatna, gdy chcesz aby powiązać z właściwością logiczną o nazwie IsHidden
w przeciwieństwie do IsVisible
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-21 13:01:18
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
public sealed class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var flag = false;
if (value is bool)
{
flag = (bool)value;
}
else if (value is bool?)
{
var nullable = (bool?)value;
flag = nullable.GetValueOrDefault();
}
if (parameter != null)
{
if (bool.Parse((string)parameter))
{
flag = !flag;
}
}
if (flag)
{
return Visibility.Visible;
}
else
{
return Visibility.Collapsed;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var back = ((value is Visibility) && (((Visibility)value) == Visibility.Visible));
if (parameter != null)
{
if ((bool)parameter)
{
back = !back;
}
}
return back;
}
}
A następnie podaj true lub false jako ConverterParameter
<Grid.Visibility>
<Binding Path="IsYesNoButtonSetVisible" Converter="{StaticResource booleanToVisibilityConverter}" ConverterParameter="true"/>
</Grid.Visibility>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-27 05:31:26
Napisz własne jest najlepszym rozwiązaniem na razie. Oto przykład konwertera, który może wykonać zarówno normalną, jak i odwróconą. Jeśli masz z tym jakieś problemy, po prostu pytaj.
[ValueConversion(typeof(bool), typeof(Visibility))]
public class InvertableBooleanToVisibilityConverter : IValueConverter
{
enum Parameters
{
Normal, Inverted
}
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
var boolValue = (bool)value;
var direction = (Parameters)Enum.Parse(typeof(Parameters), (string)parameter);
if(direction == Parameters.Inverted)
return !boolValue? Visibility.Visible : Visibility.Collapsed;
return boolValue? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return null;
}
}
<UserControl.Resources>
<Converters:InvertableBooleanToVisibilityConverter x:Key="_Converter"/>
</UserControl.Resources>
<Button Visibility="{Binding IsRunning, Converter={StaticResource _Converter}, ConverterParameter=Inverted}">Start</Button>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-18 13:56:36
Istnieje również projekt Konwertery WPF Na Codeplex. W ich dokumentacji mówią, że możesz użyć ich MapConverter do konwersji z wyliczenia widoczności na bool
<Label>
<Label.Visible>
<Binding Path="IsVisible">
<Binding.Converter>
<con:MapConverter>
<con:Mapping From="True" To="{x:Static Visibility.Visible}"/>
<con:Mapping From="False" To="{x:Static Visibility.Hidden}"/>
</con:MapConverter>
</Binding.Converter>
</Binding>
</Label.Visible>
</Label>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-05-31 08:45:26
Jeszcze jeden sposób powiązania wartości Boolean ViewModel (IsButtonVisible) z właściwością XAML Control Visibility. Bez kodowania, bez konwersji, tylko stylizacja.
<Style TargetType={x:Type Button} x:Key="HideShow">
<Style.Triggers>
<DataTrigger Binding="{Binding IsButtonVisible}" Value="False">
<Setter Property="Visibility" Value="Hidden"/>
</DataTrigger>
</Style.Triggers>
</Style>
<Button Style="{StaticResource HideShow}">Hello</Button>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-11 16:20:48
Lub prawdziwy lazy mans sposób, po prostu skorzystać z tego, co jest już i odwrócić to:
public class InverseBooleanToVisibilityConverter : IValueConverter
{
private BooleanToVisibilityConverter _converter = new BooleanToVisibilityConverter();
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var result = _converter.Convert(value, targetType, parameter, culture) as Visibility?;
return result == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var result = _converter.ConvertBack(value, targetType, parameter, culture) as bool?;
return result == true ? false : true;
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-24 05:53:57
Właśnie napisałam post na ten temat. Użyłem podobnego pomysłu jak Michael Hohlios. Tylko, że użyłem właściwości zamiast "parametru obiektu".
Powiązanie widoczności z wartością bool w WPF
Korzystanie z właściwości czyni go bardziej czytelnym, moim zdaniem.
<local:BoolToVisibleOrHidden x:Key="BoolToVisConverter" Collapse="True" Reverse="True" />
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-02-22 22:56:14
Oto jeden, który napisałem i używam dużo. Używa parametru boolean converter, który wskazuje, czy odwrócić wartość, a następnie używa XOR do wykonania negacji:
[ValueConversion(typeof(bool), typeof(System.Windows.Visibility))]
public class BooleanVisibilityConverter : IValueConverter
{
System.Windows.Visibility _visibilityWhenFalse = System.Windows.Visibility.Collapsed;
/// <summary>
/// Gets or sets the <see cref="System.Windows.Visibility"/> value to use when the value is false. Defaults to collapsed.
/// </summary>
public System.Windows.Visibility VisibilityWhenFalse
{
get { return _visibilityWhenFalse; }
set { _visibilityWhenFalse = value; }
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool negateValue;
Boolean.TryParse(parameter as string, out negateValue);
bool val = negateValue ^ System.Convert.ToBoolean(value); //Negate the value when negateValue is true using XOR
return val ? System.Windows.Visibility.Visible : _visibilityWhenFalse;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
bool negateValue;
Boolean.TryParse(parameter as string, out negateValue);
if ((System.Windows.Visibility)value == System.Windows.Visibility.Visible)
return true ^ negateValue;
else
return false ^ negateValue;
}
}
Oto tabela prawdy XOR dla odniesienia:
XOR
x y XOR
---------
0 0 0
0 1 1
1 0 1
1 1 0
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-27 16:29:38
Jeśli nie lubisz pisać niestandardowego konwertera, możesz użyć wyzwalaczy danych, aby rozwiązać ten problem:
<Style.Triggers>
<DataTrigger Binding="{Binding YourBinaryOption}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding YourBinaryOption}" Value="False">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-02 20:38:16
Napisz własną konwersję.
public class ReverseBooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// your converter code here
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-02-10 22:45:44
Szukałem bardziej ogólnej odpowiedzi, ale nie mogłem jej znaleźć. Napisałem konwerter, który może pomóc innym.
Opiera się na tym, że musimy wyróżnić sześć różnych przypadków:
- True 2 Visible, False 2 Hidden
- True 2 Visible, False 2 Fallen
- True 2 Hidden, False 2 Visible
- True 2 Fallen, False 2 Visible
- True 2 Hidden, False 2 Fallen
- True 2, False 2 Hidden
Oto moja implementacja dla pierwszych 4 przypadków:
[ValueConversion(typeof(bool), typeof(Visibility))]
public class BooleanToVisibilityConverter : IValueConverter
{
enum Types
{
/// <summary>
/// True to Visible, False to Collapsed
/// </summary>
t2v_f2c,
/// <summary>
/// True to Visible, False to Hidden
/// </summary>
t2v_f2h,
/// <summary>
/// True to Collapsed, False to Visible
/// </summary>
t2c_f2v,
/// <summary>
/// True to Hidden, False to Visible
/// </summary>
t2h_f2v,
}
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
var b = (bool)value;
string p = (string)parameter;
var type = (Types)Enum.Parse(typeof(Types), (string)parameter);
switch (type)
{
case Types.t2v_f2c:
return b ? Visibility.Visible : Visibility.Collapsed;
case Types.t2v_f2h:
return b ? Visibility.Visible : Visibility.Hidden;
case Types.t2c_f2v:
return b ? Visibility.Collapsed : Visibility.Visible;
case Types.t2h_f2v:
return b ? Visibility.Hidden : Visibility.Visible;
}
throw new NotImplementedException();
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
var v = (Visibility)value;
string p = (string)parameter;
var type = (Types)Enum.Parse(typeof(Types), (string)parameter);
switch (type)
{
case Types.t2v_f2c:
if (v == Visibility.Visible)
return true;
else if (v == Visibility.Collapsed)
return false;
break;
case Types.t2v_f2h:
if (v == Visibility.Visible)
return true;
else if (v == Visibility.Hidden)
return false;
break;
case Types.t2c_f2v:
if (v == Visibility.Visible)
return false;
else if (v == Visibility.Collapsed)
return true;
break;
case Types.t2h_f2v:
if (v == Visibility.Visible)
return false;
else if (v == Visibility.Hidden)
return true;
break;
}
throw new InvalidOperationException();
}
}
Przykład:
Visibility="{Binding HasItems, Converter={StaticResource BooleanToVisibilityConverter}, ConverterParameter='t2v_f2c'}"
Myślę, że parametry są łatwe do zapamiętania.
Mam nadzieję, że to komuś pomoże.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-10 23:12:28
Możesz użyć QuickConverter.
Z QuickConverter można zapisać logikę konwertera inline z BindingExpression
Oto odwrócony konwerter Booleant:
Visibility="{qc:Binding '!$P ? Visibility.Visible : Visibility.Collapsed', P={Binding Example}}"
Możesz dodać QuickConverter przez NuGet. Zapoznaj się z dokumentacją konfiguracji. Link: https://quickconverter.codeplex.com/
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-16 11:24:43
Prosta Wersja jednokierunkowa, która może być używana tak:
Visibility="{Binding IsHidden, Converter={x:Static Ui:Converters.BooleanToVisibility}, ConverterParameter=true}
Można zaimplementować w następujący sposób:
public class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var invert = false;
if (parameter != null)
{
invert = Boolean.Parse(parameter.ToString());
}
var booleanValue = (bool) value;
return ((booleanValue && !invert) || (!booleanValue && invert))
? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-04 19:32:16
Konwertuj wszystko na wszystko (bool,string,enum,itp.):
public class EverythingConverterValue
{
public object ConditionValue { get; set; }
public object ResultValue { get; set; }
}
public class EverythingConverterList : List<EverythingConverterValue>
{
}
public class EverythingConverter : IValueConverter
{
public EverythingConverterList Conditions { get; set; } = new EverythingConverterList();
public object NullResultValue { get; set; }
public object NullBackValue { get; set; }
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
return Conditions.Where(x => x.ConditionValue.Equals(value)).Select(x => x.ResultValue).FirstOrDefault() ?? NullResultValue;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return Conditions.Where(x => x.ResultValue.Equals(value)).Select(x => x.ConditionValue).FirstOrDefault() ?? NullBackValue;
}
}
Przykłady XAML:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:conv="clr-namespace:MvvmGo.Converters;assembly=MvvmGo.WindowsWPF"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<conv:EverythingConverter x:Key="BooleanToVisibilityConverter">
<conv:EverythingConverter.Conditions>
<conv:EverythingConverterValue ResultValue="{x:Static Visibility.Visible}">
<conv:EverythingConverterValue.ConditionValue>
<sys:Boolean>True</sys:Boolean>
</conv:EverythingConverterValue.ConditionValue>
</conv:EverythingConverterValue>
<conv:EverythingConverterValue ResultValue="{x:Static Visibility.Collapsed}">
<conv:EverythingConverterValue.ConditionValue>
<sys:Boolean>False</sys:Boolean>
</conv:EverythingConverterValue.ConditionValue>
</conv:EverythingConverterValue>
</conv:EverythingConverter.Conditions>
</conv:EverythingConverter>
<conv:EverythingConverter x:Key="InvertBooleanToVisibilityConverter">
<conv:EverythingConverter.Conditions>
<conv:EverythingConverterValue ResultValue="{x:Static Visibility.Visible}">
<conv:EverythingConverterValue.ConditionValue>
<sys:Boolean>False</sys:Boolean>
</conv:EverythingConverterValue.ConditionValue>
</conv:EverythingConverterValue>
<conv:EverythingConverterValue ResultValue="{x:Static Visibility.Collapsed}">
<conv:EverythingConverterValue.ConditionValue>
<sys:Boolean>True</sys:Boolean>
</conv:EverythingConverterValue.ConditionValue>
</conv:EverythingConverterValue>
</conv:EverythingConverter.Conditions>
</conv:EverythingConverter>
<conv:EverythingConverter x:Key="MarriedConverter" NullResultValue="Single">
<conv:EverythingConverter.Conditions>
<conv:EverythingConverterValue ResultValue="Married">
<conv:EverythingConverterValue.ConditionValue>
<sys:Boolean>True</sys:Boolean>
</conv:EverythingConverterValue.ConditionValue>
</conv:EverythingConverterValue>
<conv:EverythingConverterValue ResultValue="Single">
<conv:EverythingConverterValue.ConditionValue>
<sys:Boolean>False</sys:Boolean>
</conv:EverythingConverterValue.ConditionValue>
</conv:EverythingConverterValue>
</conv:EverythingConverter.Conditions>
<conv:EverythingConverter.NullBackValue>
<sys:Boolean>False</sys:Boolean>
</conv:EverythingConverter.NullBackValue>
</conv:EverythingConverter>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-18 10:53:41
Wiem, że to jest przestarzałe, ale nie musisz niczego ponownie wdrażać.
To co zrobiłem to zanegowanie wartości nieruchomości w ten sposób:
<!-- XAML code -->
<StackPanel Name="x" Visibility="{Binding Path=Specials, ElementName=MyWindow, Converter={StaticResource BooleanToVisibilityConverter}}"></StackPanel>
<StackPanel Name="y" Visibility="{Binding Path=NotSpecials, ElementName=MyWindow, Converter={StaticResource BooleanToVisibilityConverter}}"></StackPanel>
....
//Code behind
public bool Specials
{
get { return (bool) GetValue(SpecialsProperty); }
set
{
NotSpecials= !value;
SetValue(SpecialsProperty, value);
}
}
public bool NotSpecials
{
get { return (bool) GetValue(NotSpecialsProperty); }
set { SetValue(NotSpecialsProperty, value); }
}
I działa dobrze!
Czy coś przeoczyłem?Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-03 17:40:06