【问题标题】:How to get the value of an inherited FontSize property in an UserControl?如何获取 UserControl 中继承的 FontSize 属性的值?
【发布时间】:2011-11-06 02:56:42
【问题描述】:

我正在开发 Windows Phone 7.1 应用程序。 我有一个UserControl,它有一堆 Silverlight 子控件。大多数这些子控件的字体大小可以与上述 UserControl 的宿主相同(无论如何都会从宿主继承)。

但是对于其中一个子控件,我想将 FontSize 设置为 UserControl 的 FontSize 的一半。如果主机的 FontSize 发生变化,我希望它更新。 但是现在在 UserControl 设计期间,由于没有主机,我无法完成这项工作。执行0.5*FontSize 之类的操作会导致某些默认值 FontSize 并且在 FontSize 更改时不会更新。

我应该怎么做才能让它发挥作用?

【问题讨论】:

    标签: wpf silverlight windows-phone-7


    【解决方案1】:

    您可以将 FontSize 属性绑定到 UserControl 的 FontSize 属性,并使用转换器来计算比例。

    这是一个页面内带有文本块的示例:

    <TextBlock FontSize="{Binding ElementName=MyPage, Path=FontSize, 
     Converter={StaticResource FontSizeConverter}}" 
     Text="any text" />
    

    以及转换器(在 App.xaml 文件中声明为资源:

    public class FontSizeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var valueToConvert = value == null ? 0 : System.Convert.ToDouble(value);
    
            return valueToConvert * 0.5;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException("no use");
        }
    }
    

    【讨论】:

    • 我通过实施您建议的方式使其工作。谢谢。
    猜你喜欢
    • 2012-04-22
    • 2014-08-10
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    • 2010-10-05
    • 1970-01-01
    相关资源
    最近更新 更多