gpt4 book ai didi

css - 'em' 单元的 WPF 类比

转载 作者:技术小花猫 更新时间:2023-10-29 10:59:40 27 4
gpt4 key购买 nike

CSS 的 WPF 类比是什么 em单位?

最佳答案

这是我做的。创建了一个 MarkupExtension,它根据在 Window 上分配的字体将字体大小转换为 EM。

我要感谢 http://10rem.net/blog/2011/03/09/creating-a-custom-markup-extension-in-wpf-and-soon-silverlight

http://tomlev2.wordpress.com/tag/markup-extension/

用于提供所需的知识。

[MarkupExtensionReturnType(typeof(double))]
public class EmFontSize : MarkupExtension
{
public EmFontSize() { }

public EmFontSize(double size)
{
Size = size;
}

[ConstructorArgument("size")]
public double Size { get; set; }

public override object ProvideValue(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
return null;

// get the target of the extension from the IServiceProvider interface
IProvideValueTarget ipvt = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));
if (ipvt.TargetObject.GetType().FullName == "System.Windows.SharedDp")
return this;

DependencyObject targetObject = ipvt.TargetObject as DependencyObject;

var window = TryFindParent<Window>(targetObject);
if (window != null)
{
return window.FontSize * Size;
}
return 12 * Size;
}

public static T TryFindParent<T>(DependencyObject child) where T : DependencyObject
{
//get parent item
DependencyObject parentObject = GetParentObject(child);

//we've reached the end of the tree
if (parentObject == null) return null;

//check if the parent matches the type we're looking for
T parent = parentObject as T;
if (parent != null)
{
return parent;
}
else
{
//use recursion to proceed with next level
return TryFindParent<T>(parentObject);
}
}

public static DependencyObject GetParentObject(DependencyObject child)
{
if (child == null) return null;

//handle content elements separately
ContentElement contentElement = child as ContentElement;
if (contentElement != null)
{
DependencyObject parent = ContentOperations.GetParent(contentElement);
if (parent != null) return parent;

FrameworkContentElement fce = contentElement as FrameworkContentElement;
return fce != null ? fce.Parent : null;
}

//also try searching for parent in framework elements (such as DockPanel, etc)
FrameworkElement frameworkElement = child as FrameworkElement;
if (frameworkElement != null)
{
DependencyObject parent = frameworkElement.Parent;
if (parent != null) return parent;
}

//if it's not a ContentElement/FrameworkElement, rely on VisualTreeHelper
return VisualTreeHelper.GetParent(child);
}
}

示例用法

xmlns:my="clr-namespace:FontSizeExample"
<TextBlock Text="Sample Font" FontSize="{my:EmFontSize 1.1}"/>
<TextBlock Text="Sample Font" FontSize="{my:EmFontSize .9}"/>

关于css - 'em' 单元的 WPF 类比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/653918/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com