从WPF样式访问元素

时间:2017-05-04 08:29:56

标签: c# wpf

我在ResourceDictionary中声明了一个样式,如此。

<Style x:Key="MapMarkerLabelStyle" TargetType="{x:Type TextBlock}">
    <Setter Property="RenderTransform">
        <Setter.Value>
            <TranslateTransform X="{Binding ActualWidth,                                              
                 Converter={StaticResource DoubleMultiplierConverter}, 
                                            ConverterParameter=-0.5}" 
                                Y="-62"></TranslateTransform>
        </Setter.Value>
    </Setter>
</Style>

和文本块

<TextBlock Style="{StaticResource MapMarkerLabelStyle}" />

转换器:

public class DoubleMultiplierConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var originalValue = (double) value;
        var format = new NumberFormatInfo {NumberDecimalSeparator = "."};
        var multiplier = System.Convert.ToDouble(parameter, format);
        return originalValue * multiplier;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

在translate转换中,我需要访问textblock ActualWidth属性,但无法弄清楚绑定的外观。

2 个答案:

答案 0 :(得分:1)

试试这个。

 <TranslateTransform X="{Binding RelativeSource={RelativeSource Self}, 
                          Path=ActualWidth,                                              
             Converter={StaticResource DoubleMultiplierConverter}, 
             ConverterParameter=-0.5}" 
                     Y="-62">
 </TranslateTransform>

答案 1 :(得分:1)

Binding缺少一个合适的源对象。要绑定到TextBlock的ActualWidth属性,您应该像这样设置RelativeSource

<Style x:Key="MapMarkerLabelStyle" TargetType="TextBlock">
    <Setter Property="RenderTransform">
        <Setter.Value>
            <TranslateTransform
                X="{Binding Path=ActualWidth,
                            RelativeSource={RelativeSource AncestorType=TextBlock}
                            Converter={StaticResource DoubleMultiplierConverter}, 
                            ConverterParameter=-0.5}" 
                Y="-62"/>
        </Setter.Value>
    </Setter>
</Style>