zoukankan      html  css  js  c++  java
  • 实用的MVVM:ImageView

    最近在学习WPF,遇到一本入门好书,推荐给大家《Windows Presentation Foundation 4.5 Cookbook》

    做项目首先要从MVVM开始,现在把他的Simple MVVM例子介绍给大家,感觉简单但很实用

    1. App.xaml.cs中重载OnStartup

    protected override void OnStartup(StartupEventArgs e) {
        base.OnStartup(e);
        var mainWindow = new MainWindow();
        mainWindow.DataContext = new ImageData();
        mainWindow.Show();
    }

    2. ViewModel的实现

     public  class ImageData:INotifyPropertyChanged
      {
          public ImageData()
          {
              _openImageFileCommand = new OpenImageFileCommand(this);
              _zoomCommand = new ZoomCommand(this);
    
          }
          public ICommand OpenImageFileCommand { get { return _openImageFileCommand; } }
          public ICommand ZoomCommand { get { return _zoomCommand; } }
          public string ImagePath
            {
                get { return _imagePath; }
                set
                {
                    _imagePath = value;
                    this.RaisePropertyChanged("ImagePath");
                }
            }
          public double Zoom
          {
              get { return _zoom; }
              set
              {
                  _zoom = value;
                  this.RaisePropertyChanged("Zoom");
              }
          }
          private void RaisePropertyChanged(string propertyName)
            {
                var handler = PropertyChanged;
                if (handler == null)
                    return;
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
          public event PropertyChangedEventHandler PropertyChanged;
          private double _zoom = 1.0;
          private string _imagePath;
          private OpenImageFileCommand _openImageFileCommand;
          private ZoomCommand _zoomCommand;
      }
    View Code

    3. 下面看看View是怎么做的,除了Xaml加绑定,不再需要其它多余的代码了。

    <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:local="clr-namespace:CH07.RoutedCommands" 
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" 
        x:Class="CH07.RoutedCommands.MainWindow"
        d:DataContext="{d:DesignInstance Type=local:ImageData, IsDesignTimeCreatable=True}"
        Title="Image Viewer" Height="350" Width="525">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition />
            </Grid.RowDefinitions>
            <ToolBar FontSize="14">
                <Button Content="Open..." Command="{Binding OpenImageFileCommand}" Margin="6"/>
                <Button Content="Zoom In" Command="{Binding ZoomCommand}" CommandParameter="ZoomIn" Margin="6"/>
                <Button Content="Zoom Out" Command="{Binding ZoomCommand}" CommandParameter="ZoomOut" Margin="6"/>
                <Button Content="Normal" Command="{Binding ZoomCommand}" CommandParameter="ZoomNormal" Margin="6"/>
            </ToolBar>
            <ScrollViewer Grid.Row="1" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
                <Image Source="{Binding ImagePath}" Stretch="None">
                    <Image.LayoutTransform>
                        <ScaleTransform ScaleX="{Binding Zoom}" ScaleY="{Binding Zoom}" />
                    </Image.LayoutTransform>
                </Image>
            </ScrollViewer>
        </Grid>
    </Window>
    View Code

    4. 还有ViewModel里的Command
    ZoomCommand里的代码

       public class ZoomCommand:ICommand
        {
            public ZoomCommand(ImageData data)
            {
                _data = data;
            }
            public bool CanExecute(object parameter)
            {
                if (_data.ImagePath == null)
                    return false;
                return _data.ImagePath.IsPicture();
            }
    
            public event EventHandler CanExecuteChanged
            {
                add { CommandManager.RequerySuggested += value; }
                remove { CommandManager.RequerySuggested -= value; }
            }
            private ImageData _data;
    
            public void Execute(object parameter)
            {
                var zoomType = (ZoomType)Enum.Parse(typeof(ZoomType), (string)parameter, true);
                switch (zoomType)
                {
                    case ZoomType.ZoomIn:
                        _data.Zoom *= 1.2;
                        break;
                    case ZoomType.ZoomOut:
                        _data.Zoom /= 1.2;
                        break;
                    case ZoomType.ZoomNormal:
                        _data.Zoom = 1.0;
                        break;
                    default:
                        break;
                }
            }
        }
        enum ZoomType
        {
            ZoomIn,
            ZoomOut,
            ZoomNormal
        }
    View Code

    下面是OpenImageFileCommand

      public class OpenImageFileCommand:ICommand
        {
            public OpenImageFileCommand(ImageData data)
            {
                _data = data;
            }
            public bool CanExecute(object parameter)
            {
                return true;
            }
    
            public event EventHandler CanExecuteChanged;
    
            private ImageData _data;
    
            public void Execute(object parameter)
            {
                var dlg = new OpenFileDialog
                {
                    Filter = "图形 文件|*.jpg;*.png;*.bmp;*.gif"
                };
    
                if (dlg.ShowDialog()==true)
                {
                    _data.ImagePath = dlg.FileName;
                }
            }
        }
    View Code

    5. 其它
    判断打开的文件类型

           public static bool IsPicture(this string filePath)
            {
                try
                {
                    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    BinaryReader reader = new BinaryReader(fs);
                    string fileClass;
                    byte buffer;
                    byte[] b = new byte[2];
                    buffer = reader.ReadByte();
                    b[0] = buffer;
                    fileClass = buffer.ToString();
                    buffer = reader.ReadByte();
                    b[1] = buffer;
                    fileClass += buffer.ToString();
    
    
                    reader.Close();
                    fs.Close();
                    ////255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar 
                    return ((fileClass == "255216" || fileClass == "7173" || fileClass == "6677" || fileClass == "13780") ? true : false);
                   
                }
                catch
                {
                    return false;
                }
            }
    View Code
  • 相关阅读:
    存储过程,触发器,函数 学习总结
    发布软件之前,怎样告诉用户怎么用
    一种小项目开发结构
    错误记录 两种实现方法
    模具行业生产知识
    请大家警惕这个散播木马的网站 www.zzyqr.com,本文简要地分析了它通过网页的传播方式
    如何保证开发过程中对数据库结构的更新顺利地迁移到产品服务器上。
    三层开发中容易犯的错误
    全局程序集缓存导致cs0006编译错误:找不到元数据文件错误
    for VS. foreach 那个性能更高,为什么,怎么选择
  • 原文地址:https://www.cnblogs.com/joe62/p/3673843.html
Copyright © 2011-2022 走看看