简体   繁体   中英

Converter doesn't get called

I declared converter in xaml:

<local:StringToWidthConverter x:Key="Converter" />

and

<GridViewColumn Header="Monitor 4"
                Width="{Binding Monitor4, Converter={StaticResource Converter}, ConverterParameter=Auto}">

Converter class defined as:

public class StringToWidthConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (string)value == null ? 0.0 : parameter;
    }

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

Monitor4 definition is:

public string Monitor4
{
    get { return monitor4; }
    set
    {
        monitor4 = value;
        OnPropertyChanged("Monitor4");
    }
}

but the converter never get called? any suggestion would be great. Thank you in advance.

The only cause I can think of is you forget to set the DataContext so there is no source to bind at all.

this.DataContext = The_View_Model; 

If the DataContext is set properly, how do you know the converter is not executed? Set a breakpoint in the Convert method, is breakpoint hit or not?

If you have set the DataContext properly and some binding is not working, look at the Output window, there should be some binding error - unlike unhandled exceptions, VS just logs the binding errors silently without terminating the app.

For example, if you bind to a property Monitor4 which turns out to be nonexistent:

System.Windows.Data Error: 40 : BindingExpression path error: 'Monitor4' property not found on 'object' ''ConverterWindow' (Name='')'. BindingExpression:Path=Monitor4; DataItem='ConverterWindow' (Name=''); target element is 'Grid' (Name=''); target property is 'Width' (type 'Double')

If the value converter is not working correctly

System.Windows.Data Error: 6 : 'DynamicValueConverter' converter failed to convert value 'Auto' (type 'String')

In your case, you cannot convert a string value Auto to a Double . You can return System.Double.NaN instead.

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    return (string)value == null ? 0.0 : System.Double.NaN; 
}

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