转换器仅触发一次而不是每次标签内容更改

时间:2016-04-21 15:21:25

标签: c# wpf mvvm ivalueconverter

我的标签宽度为auto,绑定到string类型的属性。

<Label x:Name="ExampleLabel" Content="{Binding ExampleProperty}"Height="30" Width="Auto" >

然后我有一个绑定到该标签宽度的属性。转换器应将宽度转换为负值。

<UserControl.Resources>
        <c:PositiveToNegativeConverter x:Key="PositiveToNegativeConverter"/>
</UserControl.Resources>

"{Binding ElementName=ExampleLabel, Path=Width, Converter={StaticResource PositiveToNegativeConverter}}"

我希望转换器在标签内容更改时执行,但只在应用程序加载时触发一次。

这是我的转换器

public class PositiveToNegativeConverter : IValueConverter
{
    public object Convert(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        return (double)value * -1;
    }

    public object ConvertBack(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        return Math.Abs((double) value);
    }
}

非常感谢任何帮助。感谢。

1 个答案:

答案 0 :(得分:1)

如果绑定到ActualWidth而不是Width,它是否有效? Width只是最后分配给Width属性的值,而ActualWidth是一个只读的实时更新运行时值,用于确定事物的真实范围在UI中。

我希望在你想要的时候更新:

"{Binding ElementName=ExampleLabel, Path=ActualWidth, Converter={StaticResource PositiveToNegativeConverter}}"
相关问题