none
xaml 中怎么写Imagesource的convert? RRS feed

  • 问题

  •  <ImageSource.Binding>
                                <Binding.Converter>

    这样貌似不行,有没有直接在xaml文件里面写ImageSource的converter方法呢?来点代码瞧瞧?多谢

    2011年9月19日 1:06

答案

  • 可以啊,别忘了指定ImageDrawing的Rect属性:

    <Window x:Class="WpfApplication2.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfApplication2"
            Title="MainWindow" Height="350" Width="525">
      <Grid>
        <Image>
          <Image.Source>
            <DrawingImage>
              <DrawingImage.Drawing>
                <ImageDrawing Rect="0,0,1,1">
                  <ImageDrawing.ImageSource>
                    <Binding Path="ImageUriPath" Mode="OneWay">
                      <Binding.Converter>
                        <local:ImageSourceConverter/>
                      </Binding.Converter>
                    </Binding>
                  </ImageDrawing.ImageSource>
                </ImageDrawing>
              </DrawingImage.Drawing>
            </DrawingImage>
          </Image.Source>
        </Image>
      </Grid>
    </Window>
    
    

    C#:

      public partial class MainWindow : Window
      {
        public MainWindow()
        {
          InitializeComponent();
    
          this.DataContext = new ImageItem() { ImageUriPath = @"image.png" };
        }
      }
    
      public class ImageItem
      {
        public string ImageUriPath { get; set; }
      }
    
      public class ImageSourceConverter : IValueConverter
      {
        #region IValueConverter Members
    
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
          return (string)value;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
          throw new NotImplementedException();
        }
    
        #endregion
      }
    

    或者:

      public class ImageSourceConverter : IValueConverter
      {
        #region IValueConverter Members
    
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
          return new BitmapImage(new Uri("pack://application:,,,/" + (string)value, UriKind.RelativeOrAbsolute));
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
          throw new NotImplementedException();
        }
    
        #endregion
      }
    

    Sincerely,


    Bob Bao [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    2011年9月19日 16:30
    版主