简体   繁体   中英

c# wpf IValueConverter and property attributes

I have a text box that is bound to a property (eventually a lot of those). The property is a numerical value. When displaying this numerical value i would like to add a unit to it (like V,mV, C etc) and optionally scale it (as for example 3200mV=3.2V). Currently I am using one value converter and supplying a unit as a converter parameter, however i would still need a converter to pass it back.

However what i would like to do is add a custom attribute to a property with the required scale and unit. Something like this:

[Unit("mV")]
[Scale(0.1)]
public uint MyProperty
{
    get{ return myProperty}
    set
    {
       if(value==myProperty)
         return;
       myProperty=value;
       OnPropertyChanged("MyProperty");    
    }
}

However I don't know how could it be possible to pass such information to the converter (and if it even is possible)?

Or what other possibilities could there be to do this in a nice way?

To get the attribute values from the UnitAttribute and ScaleAttribute, the value converter must use Reflection and has to know the name of the class these properties are in and the name of the specific property to convert.

You can add a DependencyProperty for the class name to your value converter and use it as follows:

<UserControl.Resources>
    <local:MyUnitConverter x:Key="myUnitConverter" ClassName="MyNamespace.MyClass" />
</UserControl.Resources>

and then use the converter on the property and also pass the name of the property as the ConverterParameter:

<TextBlock Text="{Binding MyProperty, Converter={StaticResource myUnitConverter},
    ConverterParameter=MyProperty}" />

Then it should be possible from the converter to find the values used in the attributes and convert the property accordingly.

public class MyUnitConverter : DependencyObject, IValueConverter
{
    // add dependency property ClassName as string

    public object Convert(object value, Type targetType, object parameter, CultureInfo info)
    {
        // use dependency property ClassName and (string)parameter 
        // as property name to get the attribute values using Reflection.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM