实用的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

 

 

 

 

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/joe62/p/3673843.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Windows Presentation Foundation 4.5 Cookbook的源码 Chapter 1: Foundations 7 Introduction 7 Creating custom type instances in XAML 9 Creating a dependency property 15 Using an attached property 25 Creating an attached property 28 Accessing a static property from XAML 33 Creating a custom markup extension 37 Handling routed events 44 Chapter 2: Resources 51 Introduction 51 Using logical resources 52 Dynamically binding to a logical resource 57 Using user-selected colors and fonts 59 Using binary resources 63 Accessing binary resources in code 70 Accessing binary resources from another assembly 72 Managing logical resources 76 Chapter 3: Layout and Panels 81 Introduction 81 Creating a table-like user interface 83 Dynamically sizing grid rows/columns 90 Creating a scrollable user interface 92 Creating a border around panels and elements 94 Placing elements in exact positions 96 Adding/removing elements to a panel dynamically 98 Creating a tabbed user interface 100 Implementing drag-and-drop 103 Chapter 4: Using Standard Controls 109 Introduction 109 Working with text 110 Using content controls 114 Displaying images 120 Creating tooltips 126 Creating a list of items 131 Creating a standard menu 134 Creating a context menu 137 Selecting options with checkboxes and radio buttons 139 Manipulating tab order and focus 141 Chapter 5: Application and Windows 145 Introduction 145 Creating a window 145 Creating a dialog box 149 Using the common dialog boxes 153 Creating ownership between windows 156 Creating a custom shaped window 158 Creating a single instance application 162 Handling an unhandled exception 166 Chapter 6: Data Binding 169 Introduction 169 Element to element binding 170 Binding to a single object 173 Binding to a collection 180 Using data templates 184 Using value converters 191 Creating a master-detail view 199 Sorting and filtering bound collections 202 Grouping
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值