根据背景色获取前景色。当然也可反着用 BackgroundToForegroundConverter : IValueConverter { private Color IdealTextColor(Color bg) { const int nThreshold = 105; var bgDelta = System.Convert.ToInt32((bg.R * 0.299) + (bg.G * 0.587) + (bg.B * 0.114)); var foreColor = (255 - bgDelta < nThreshold) ? Colors.Black : Colors.White; return foreColor; } public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is SolidColorBrush) { var idealForegroundColor = this.IdealTextColor(((SolidColorBrush)value).Color); var foreGroundBrush = new SolidColorBrush(idealForegroundColor); foreGroundBrush.Freeze(); return foreGroundBrush; } return Brushes.White; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return DependencyProperty.UnsetValue; } }
PercentToAngleConverter.cs代码:
百分比转换为角度值 PercentToAngleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var percent = value.ToSafeString().ToDouble(); if (percent >= 1) return 360.0D; return percent * 360; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }
ThicknessToDoubleConverter.cs代码:
获取Thickness固定值double ThicknessToDoubleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var thickness = (Thickness)value; return thickness.Left; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return DependencyProperty.UnsetValue; } }
TreeViewMarginConverter.cs代码:
计算树节点的左缩进位置 TreeViewMarginConverter : IValueConverter { public double Length { get; set; } public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var item = value as TreeViewItem; if (item == null) return new Thickness(0); int dep = this.GetDepth(item); return new Thickness(Length * dep, 0, 0, 0); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return DependencyProperty.UnsetValue; } public int GetDepth(TreeViewItem item) { TreeViewItem parent; while ((parent = GetParent(item)) != null) { return GetDepth(parent) + 1; } return 0; } private TreeViewItem GetParent(TreeViewItem item) { var parent = item != null ? VisualTreeHelper.GetParent(item) : null; while (parent != null && !(parent is TreeViewItem || parent is TreeView)) { parent = VisualTreeHelper.GetParent(parent); } return parent as TreeViewItem; } }
TrueToFalseConverter.cs代码: