WPF:标准值转换器

时间:2018-01-07 13:51:51

标签: wpf xaml

所以我有一个简单的Gauge类,其中包含实现int的静态Propertychanged属性:

TotalPacketsSent

property一直在提高,我想写一个简单的converter并发送此converterproperty value并返回一些基于这个property

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
int val = (int)value;
    double percentage = ((double)MyClass.TotalPacketsSent / MyClass.TotalPacketsInList) * 100;
    return percentage;
        }

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

Window.Resources下我有这个:

<Convertors:GaugeValueConverter x:Key="GaugeValueConverter"/>

这是我的Gause

<Controllers:Gauge x:Name="gauge"
                   Value="{Binding Path=(my:MyClass.TotalPacketsSent), Converter={StaticResource GaugeValueConverter}}"
                   Minimum="0"
                   Maximum="100"/>

所以我的问题是我的converter根本不工作,我的意思是我看不到这甚至被执行了。 有什么想法吗?

编辑:

property一直在变化,我Label我正在使用这种方式来展示其价值:

Content="{Binding Path=(my:MyClass.TotalPacketsSent)}"

这很好用。

1 个答案:

答案 0 :(得分:0)

您将value参数转换为int,然后不再使用它。

我想你正在寻找的是(来自IMultiValueConverter而不是IValueConverter):

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
    double totalPacketsSent = (double)values[0];
    double totalPacketsInList = (double)values[1];

    // further validation for handling divide by zero, etc. may need to go here

    return totalPacketsSent / totalPacketsInList * 100
}

在XAML中:

<Controllers:Gauge x:Name="gauge" Minimum="0" Maximum="100">
    <Controllers:Gauge.Value>
        <MultiBinding Converter="{StaticResource GaugeValueConverter}">
            <Binding Path="(my:MyClass.TotalPacketsSent)" />
            <Binding Path="(my:MyClass.TotalPacketsInList)" />
        </MultiBinding>
    </Controllers:Gauge.Value>
</Controllers:Gauge>