Files
test_demo/MX-PD-盘古 - new/PanGu.DieBonderApp/MainShell/Converter/BoolToVisibleConverter.cs
Shi.Ji e31d3560bb 添加 MX-PD-盘古 项目文件
将 MX-PD-盘古 - new 目录下的所有文件添加到主仓库
2026-05-18 11:43:09 +08:00

95 lines
3.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace MainShell.Converter
{
public class BoolToVisibleConverter : IValueConverter
{
// 将 bool (或可转换为 bool 的值) 转换为 Visibility
// parameter 支持:
// 包含 "invert" / "inverse" / "not" / "!" 的字符串 — 反转布尔值
// 包含 "hidden" 的字符串 — 当为 false 时返回 Visibility.Hidden 而不是 Collapsed
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool isVisible = false;
if (value is bool b)
{
isVisible = b;
}
else if (value is bool?)
{
isVisible = ((bool?)value) ?? false;
}
else if (value is string s)
{
bool.TryParse(s, out isVisible);
}
else if (value != null)
{
try
{
isVisible = System.Convert.ToBoolean(value);
}
catch
{
isVisible = false;
}
}
var paramString = parameter as string;
bool invert = false;
bool useHidden = false;
if (!string.IsNullOrEmpty(paramString))
{
var p = paramString.ToLowerInvariant();
if (p.Contains("invert") || p.Contains("inverse") || p.Contains("not") || p.Contains("!"))
invert = true;
if (p.Contains("hidden"))
useHidden = true;
}
if (invert)
isVisible = !isVisible;
return isVisible ? Visibility.Visible : (useHidden ? Visibility.Hidden : Visibility.Collapsed);
}
// 将 Visibility 转换回 bool
// Visible => trueHidden/Collapsed => false
// 支持与 Convert 相同的 parameter 反转语义
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is Visibility))
return Binding.DoNothing;
var vis = (Visibility)value;
bool result = vis == Visibility.Visible;
var paramString = parameter as string;
if (!string.IsNullOrEmpty(paramString))
{
var p = paramString.ToLowerInvariant();
if (p.Contains("invert") || p.Contains("inverse") || p.Contains("not") || p.Contains("!"))
result = !result;
}
if (targetType == typeof(bool) || targetType == typeof(object))
return result;
if (targetType == typeof(bool?))
return (bool?)result;
try
{
return System.Convert.ChangeType(result, targetType);
}
catch
{
return result;
}
}
}
}