简体   繁体   中英

IValueConverter gets null value - WPF C#

I am trying to use CroppedBitmap.

The path of the image is known only during run time, so I want to set CroppedBitomap.Source via Binding.

I found out that there is a known issue with CroppedBitmap and its Source. see: WPF - using CroppedBitmap in DataTemplate

These link recommend to use a converter. I tried doing it, but I always get null value inside the Convert function.

Here is a xaml view:

<UserControl> 
    <UserControl.Resources>
        <local:ImageConverter x:Key="imageConverter" />
    </UserControl.Resources>

    <StackPanel>
        <Label x:Name="testLabel" Content="{Binding Path=Img}"/>
        <Button x:Name="testButton" Content="{Binding ElementName=testLabel, Path=Content}"/>

        <Image Stretch="None">
            <Image.Source>
                <CroppedBitmap Source="{Binding ElementName=testLabel, Path=Content, Converter={StaticResource imageConverter}}" SourceRect="10,10,50,50" />            
            </Image.Source>
        </Image>
    </StackPanel>
</UserControl>

The label named "testLabel" shows the value from the property Img with no problem. The button "testButton" shows the same value as "testLabel".

Here is the class imageConverter:

public class ImageConverter : IValueConverter
{
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            FormatConvertedBitmap fcb = new FormatConvertedBitmap();
            fcb.BeginInit();
            fcb.Source = new BitmapImage(new Uri((string)value));
            fcb.EndInit();
            return fcb;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException("Cannot convert back");
        }
}

But when I debug the function Convert I see that the first argument named "value" always gets null.

Gurus, I need your help.

I had the same problem.

My error was that the bound Property was the wrong type. It was string should have been an enum.

No build error. But at run time my (IValueConverter).Convert method gets passed value=null.

Where this happens - check the bindings ...

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