溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何在C#中使用Image控件

發(fā)布時間:2021-03-02 16:25:57 來源:億速云 閱讀:330 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章給大家介紹如何在C#中使用Image控件,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

首先是View層,比較簡單:

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

然后我們再來看看Model層也很簡單。

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í)際返回的是一個BitmapImage對象。所以我們在寫程序綁定的時候一定要弄清綁定的目標(biāo)和對象之間的關(guān)系,這個是非常重要的。

下面就是在ViewModel層中來添加綁定,并更新數(shù)據(jù)源,這里使用的是一個定時器來定時更新數(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í)例化一個ViewModel對象綁定到前臺中,這個思路其實(shí)是相當(dāng)明確的。

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

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

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

<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è)置當(dāng)前圖片的生成操作為Resource。

關(guān)于如何在C#中使用Image控件就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI