Image Binding

  • 1149
  • 0

摘要:Image Binding

這裡Binding實作的方式,是專案裡有把圖檔加進來,開放一個string屬性,內容是這個圖檔的檔名,xaml裡有一個image,它的source binding到這個string 屬性,再加上一個Converter,在Converter產生image然後回傳。

看一下 c# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace ImageBindingTest
{
    public class vm
    {
        string img;

        public string Img
        {
            get { return img; }
            set { img = value; }
        }
        BitmapImage bitmapimg;

        public vm()
        {
            img = "7-11_2.BMP";

        }
    }
}

Converter:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace ImageBindingTest
{
    public class MyImageConverter:IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if ((value!=null)&&(value.ToString()!=null))
            {
                return new BitmapImage(new Uri(value.ToString(), UriKind.RelativeOrAbsolute));
            }
            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
    }
}

xaml的code:

<Window x:Class="ImageBindingTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:ImageBindingTest"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <vm:MyImageConverter x:Key="MyImageConverter"/>
    </Window.Resources>
    <Window.DataContext>
        <vm:vm/>
    </Window.DataContext>
    <Grid>
        <Image Source="{Binding Img, Converter={StaticResource MyImageConverter}}" HorizontalAlignment="Left" Height="194" Margin="80,61,0,0" VerticalAlignment="Top" Width="352"/>

    </Grid>
</Window>