最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C# WPF Image控件的綁定方法

 更新時(shí)間:2021年03月02日 11:56:42   作者:Hello——尋夢(mèng)者!  
這篇文章主要介紹了C# WPF Image控件的綁定方法,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下

     在我們平時(shí)的開發(fā)中會(huì)經(jīng)常用到Image控件,通過設(shè)置Image控件的Source屬性,我們可以加載圖片,設(shè)置Image的source屬性時(shí)可以使用相對(duì)路徑也可以使用絕對(duì)路徑,一般情況下建議使用絕對(duì)路徑,類似于下面的形式Source="/Demo;Component/Images/Test.jpg"其中Demo表示工程的名稱,后面表示具體哪個(gè)文件夾下面的哪個(gè)圖片資源,在程序中,我們甚至可以為Image控件設(shè)置X:Name屬性,在后臺(tái)代碼中動(dòng)態(tài)去改變Image的Source,但我個(gè)人認(rèn)為這種方式不太適合最大量的圖片切換,而且增加了View層和代碼之間的耦合性,不是和復(fù)合MVVM的核心設(shè)計(jì)思想,所以今天就總結(jié)一下Image的動(dòng)態(tài)綁定的形式。

    要綁定,肯定是綁定到Image控件的Source屬性上面,我們首先要搞清楚Source的類型是什么,public ImageSource Source { get; set; }也就是ImageSource類型,當(dāng)然在我們綁定的時(shí)候用的最多的就是BitmapImage這個(gè)位圖圖像啦,我們首先來看看BitmapImage的繼承關(guān)系:BitmapImage:BitmapSource:ImageSource,最終也是一種ImageSource類型。當(dāng)然在我們的Model層中我們也可以直接定義一個(gè)BitmapImage的屬性,然后將這個(gè)屬性直接綁定到Image的Source上面,當(dāng)然這篇文章我們定義了一個(gè)ImgSource的String類型,所以必須要定義一個(gè)轉(zhuǎn)換器Converter,這里分別貼出相應(yīng)地代碼。

首先是View層,比較簡(jiǎn)單:

    <Grid Grid.Row="1">
      <Image Source="{Binding Path=LTEModel.ImgSource,Converter={StaticResource MyImageConverter}}" Stretch="Fill">
      </Image>
    </Grid>

然后我們?cè)賮砜纯碝odel層也很簡(jiǎn)單。

public class LTEModel : BaseModel
  {
    private string _imageSource = null;
    public string ImgSource
    {
      get
      {
        return _imageSource;
      }
      set
      {
        if (value != _imageSource)
        {
          _imageSource = value;
          FirePropertyChanged("ImgSource");
        }
      }
    }
  }

然后就是重要的轉(zhuǎn)換器:

public class StringToImageSourceConverter:IValueConverter
  {
    #region Converter

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
      string path = (string)value;
      if (!string.IsNullOrEmpty(path))
      {
        return new BitmapImage(new Uri(path, UriKind.Absolute));
      }
      else
      {
        return null;
      }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
      return null;
    }
    #endregion
  }

然后就是重要的轉(zhuǎn)換器:

public class StringToImageSourceConverter:IValueConverter
  {
    #region Converter

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
      string path = (string)value;
      if (!string.IsNullOrEmpty(path))
      {
        return new BitmapImage(new Uri(path, UriKind.Absolute));
      }
      else
      {
        return null;
      }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
      return null;
    }
    #endregion
  }

轉(zhuǎn)換器返回的是Object類型,實(shí)際返回的是一個(gè)BitmapImage對(duì)象。所以我們?cè)趯懗绦蚪壎ǖ臅r(shí)候一定要弄清綁定的目標(biāo)和對(duì)象之間的關(guān)系,這個(gè)是非常重要的。

下面就是在ViewModel層中來添加綁定,并更新數(shù)據(jù)源,這里使用的是一個(gè)定時(shí)器來定時(shí)更新數(shù)據(jù)源:

public class LTEViewModel : NotifyObject
  {
    private DispatcherTimer myDispatcher = null;
    private Random random = new Random();
    public LTEViewModel()
    {
      GetImageSource();
      InitTimer();
    }

    private LTEModel _lteModel = null;
    public LTEModel LTEModel
    {
      get
      {
        if (_lteModel == null)
        {
          _lteModel = new LTEModel();
        }
        return _lteModel;
      }
      set
      {
        if (value != _lteModel)
        {
          _lteModel = value;
          FirePropertyChanged("LTEModel");
        }
      }
    }

    private BaseModel _baseModel = null;
    public BaseModel BaseModelInstance
    {
      get
      {
        if (_baseModel == null)
        {
          _baseModel = new BaseModel()
          {
            Title = "分地區(qū)LTE分布",
            Time = DateTime.Now.ToString()
          };
        }
        return _baseModel;
      }
      set
      {
        if (value != _baseModel)
        {
          _baseModel = value;
          FirePropertyChanged("BaseModelInstance");
        }
      }
    }

    private List<string> imgList = new List<string>();
    private void GetImageSource()
    {
      //通過程序集來讀取相應(yīng)的資源的路徑
      string assemblyLocation = this.GetType().Assembly.Location;
      string assLocation = assemblyLocation.Substring(0, assemblyLocation.LastIndexOf("\\"));
      string[] img_files = Directory.GetFiles(string.Format("{0}\\Images", assLocation), "*.JPG");
      foreach (string img_path in img_files)
      {
        imgList.Add(img_path);
      }
    }

    private void InitTimer()
    {
      myDispatcher = new DispatcherTimer();
      myDispatcher.Tick += new EventHandler(Timer_Tick);
      myDispatcher.Interval = TimeSpan.FromMilliseconds(1000);
      myDispatcher.Start();
    }

    private void Timer_Tick(object sender, EventArgs e)
    {
      int imageIndex = 0;
      if (imgList.Count > 0 && LTEModel != null)
      {
        imageIndex = random.Next(0, imgList.Count);
        LTEModel.ImgSource = imgList[imageIndex];
      }
      if (_baseModel != null)
      {
        _baseModel.Time = DateTime.Now.ToString();
      }
    }
  }

然后就是實(shí)例化一個(gè)ViewModel對(duì)象綁定到前臺(tái)中,這個(gè)思路其實(shí)是相當(dāng)明確的。

      其實(shí)在我們的很多時(shí)候,我們并不知道我們需要綁定什么圖片,或者說根據(jù)數(shù)據(jù)類型來綁定圖片,這個(gè)在定義數(shù)據(jù)模板的時(shí)候經(jīng)常使用到,下面就介紹一下,根據(jù)類型來綁定相應(yīng)的圖片。然后通過定義 

public enum DeviceType
{  
  SheXiangJi,
  KaKou,
  DianZiJingCha,
  MingJin
}

這種類型,通過不同的類型來綁定到不同的圖片,這個(gè)也是一個(gè)非常重要的應(yīng)用,我們一定要注意使用的方法,這里只是簡(jiǎn)單介紹一下。   

<ItemsControl ItemsSource="{Binding DeviceList,RelativeSource={RelativeSource TemplatedParent}}" Grid.Row="2">
              <ItemsControl.Template>
                <ControlTemplate TargetType="ItemsControl">
                  <UniformGrid Columns="3" Rows="7" IsItemsHost="True"></UniformGrid>
                </ControlTemplate>
              </ItemsControl.Template>
              <ItemsControl.ItemTemplate>
                <DataTemplate>
                  <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" Margin="20 0 0 0" VerticalAlignment="Center" SnapsToDevicePixels="True">
                    <Image x:Name="icon1" Width="48" Height="48" RenderOptions.BitmapScalingMode="NearestNeighbor" VerticalAlignment="Center"></Image>
                    <TextBlock Margin="10 0 0 0" Foreground="#fff" ToolTip="{Binding Name}" FontSize="40" Text="{Binding Name}" HorizontalAlignment="Left" VerticalAlignment="Center"></TextBlock>
                  </StackPanel>
                  <DataTemplate.Triggers>
                    <DataTrigger Binding="{Binding Type}" Value="SheXiangJi">
                      <Setter Property="Source" Value="/IGisControls.JTJ.UIControls;component/images/camera.png" TargetName="icon1"></Setter>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Type}" Value="KaKou">
                      <Setter Property="Source" Value="/IGisControls.JTJ.UIControls;component/images/Bayonet.png" TargetName="icon1"></Setter>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Type}" Value="DianZiJingCha">
                      <Setter Property="Source" Value="/IGisControls.JTJ.UIControls;component/images/epolice.png" TargetName="icon1"></Setter>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Type}" Value="MingJin">
                      <Setter Property="Source" Value="/IGisControls.JTJ.UIControls;component/images/Police_A.png" TargetName="icon1"></Setter>
                    </DataTrigger>
                  </DataTemplate.Triggers>
                </DataTemplate>
              </ItemsControl.ItemTemplate>
            </ItemsControl>

    另外和Image很類似的就是 <ImageBrush ImageSource="/IGisControls.JTJ.UIControls;component/images/screenBG.jpg" Stretch="Fill"></ImageBrush>

用法也差不多,同樣可以通過綁定的方式來添加圖片,不過在使用的時(shí)候還是需要注意一下就是設(shè)置當(dāng)前圖片的生成操作為Resource。

以上就是C# WPF Image控件的綁定方法的詳細(xì)內(nèi)容,更多關(guān)于C# WPF Image控件的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論

慈利县| 武威市| 邓州市| 甘德县| 娱乐| 岫岩| 仙桃市| 四川省| 康定县| 云梦县| 淮北市| 镇赉县| 博爱县| 中卫市| 垫江县| 湟源县| 梅河口市| 科尔| 承德县| 柳州市| 海门市| 蓝山县| 新化县| 深圳市| 云安县| 大城县| 高碑店市| 平定县| 高邮市| 峨边| 柞水县| 刚察县| 临沧市| 仁怀市| 浠水县| 河西区| 水富县| 托克托县| 太湖县| 凌云县| 任丘市|