如何在C#中使用Image控件

发布时间:2021-03-02 16:25:57 作者:Leah
来源:亿速云 阅读:299

这篇文章给大家介绍如何在C#中使用Image控件,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

首先是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");
        }
      }
    }
  }

然后就是重要的转换器:

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
  }

然后就是重要的转换器:

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
  }

转换器返回的是Object类型,实际返回的是一个BitmapImage对象。所以我们在写程序绑定的时候一定要弄清绑定的目标和对象之间的关系,这个是非常重要的。

下面就是在ViewModel层中来添加绑定,并更新数据源,这里使用的是一个定时器来定时更新数据源:

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 = "分地区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()
    {
      //通过程序集来读取相应的资源的路径
      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();
      }
    }
  }

然后就是实例化一个ViewModel对象绑定到前台中,这个思路其实是相当明确的。

      其实在我们的很多时候,我们并不知道我们需要绑定什么图片,或者说根据数据类型来绑定图片,这个在定义数据模板的时候经常使用到,下面就介绍一下,根据类型来绑定相应的图片。然后通过定义 

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

这种类型,通过不同的类型来绑定到不同的图片,这个也是一个非常重要的应用,我们一定要注意使用的方法,这里只是简单介绍一下。   

<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>

用法也差不多,同样可以通过绑定的方式来添加图片,不过在使用的时候还是需要注意一下就是设置当前图片的生成操作为Resource。

关于如何在C#中使用Image控件就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. 如何理解Image控件中的
  2. 如何在C#应用中使用ToolStrip控件

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

image控件

上一篇:如何在python线程中使用threading.Thread()函数

下一篇:如何在java中使用ArrayList实现一个斗地主游戏

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》