Original: "Value converter" in WPF image data-bound icon object
???? This is the original code:
???? <image source= "{Binding Menuicon}"?/>
The Menuicon here is a string type, Menuicon = "/image/tux.ico".
The problem I encountered is that menuicon in a class that a colleague has encapsulated is an icon object, not a relative or absolute path, and there is no control in WPF that can directly represent an icon object, and the last thing I need to implement is to dynamically add and display these objects.
at first I was thinking that colleagues can put the value of the class types Change, but they say this will require rewriting the class. So I think it might be possible to build a temporary storage variable that takes all of the Menuicon objects inside out and transforms them, but it does increase overhead. Then can be accompanied by the time to read the direct conversion, of course, here we may be able to read the function to add a conversion method, but in that case, each of the properties of the class should be read separately, it is very troublesome, fortunately there is another way, the value of WPF converter.
[valueconversion (typeof (Icon), typeof (ImageSource))]?
public class Iconconverter:ivalueconverter???????? IValueConverter
{
??? public object Convert (object value, Type TargetType, Object parameter, CultureInfo culture)
??? {
??????? Icon icon = (icon) value;??
??????? Bitmap Bitmap = icon. Tobitmap ();
??????? IntPtr hbitmap = bitmap. Gethbitmap ();
??????? ImageSource BitmapSource =
??????? Imaging.createbitmapsourcefromhbitmap (
?????? hbitmap, IntPtr.Zero, Int32rect.empty,
??????? Bitmapsizeoptions.fromemptyoptions ());
??????? BitmapSource;
???}
? ? ///The function below is to achieve the inverse of the above conversion, we do not need to change the ImageSource into an icon, so there is no specific implementation
? ? public object Convertback (object value, Type targetType, object parameter, CultureInfo culture)
? ? {
? ? ? ? ? ? throw new NotImplementedException ();
? ? ?}
}
Finally, the data is re-bound again,
1. Add Reference: Xmlns:local = "Clr-namespace: The converter is in the same namespace"
2. Add resources: <local:iconconverter x:key= "Iconconverter"/>
3. Binding Converter Data: <image source= "{Binding Path=menuicon, Converter={staticresource Iconconverter}}"/>
OK, the problem is solved.
Value converter WPF image data-bound icon object