在运行时设置图像宽度和高度

时间:2014-05-08 14:37:55

标签: c# image silverlight windows-phone-8 windows-phone

我正在使用Windows Phone 8应用程序。

我有列表框,图像和值绑定到它。我需要在图像显示之前设置图像的宽度和高度。

列表框DataTemplate

   <DataTemplate x:Key="DataTemplate">
            <Border x:Name="ListItemBorder" 
                    Margin="0,2,0,0" 
                    VerticalAlignment="Stretch"
                    HorizontalAlignment="Stretch"

                <Grid>
                   <Image 
                     Style="{StaticResource ImageStyle}"
                     Stretch="Uniform"
                     Source="{Binding ImageName}"
                     HorizontalAlignment="Center"
                     VerticalAlignment="Center"
                     Margin="1,1,1,1"/>
               </Grid>
           </Border>
   </DataTemplate>

要获取Image的宽度和高度,请使用此代码

int width = 0;
int height = 0;
using (var stream = Application.GetResourceStream(new Uri("Assets/test.jpg", UriKind.Relative)).Stream)
{
    var bmpi = new BitmapImage();
    bmpi.SetSource(stream);
    bmpi.CreateOptions = BitmapCreateOptions.None;
    width = bmpi.PixelWidth;
    height = bmpi.PixelHeight;
    bmpi = null; // Avoids memory leaks
}

但是如何改变宽度和高度并设置呢?

1 个答案:

答案 0 :(得分:2)

将宽度和高度属性添加到XAML

<Image 
     Style="{StaticResource ImageStyle}"
     Stretch="Uniform"
     Source="{Binding ImageName}"
     HorizontalAlignment="Center"
     VerticalAlignment="Center"
     Margin="1,1,1,1"
     Width="{Binding imageWidth}" Height="{Binding imageHeight}"
/>

在后端代码中,您需要创建绑定的两个属性。

private int _imageWidth;
public int imageWidth{
   get{ return _imageWidth; }
   set{ _imageWidth = value; OnPropertyChanged("imageWidth"); }
}

private int _imageHeight;
public int imageHeight{
   get{ return _imageHeight; }
   set{ _imageHeight = value; OnPropertyChanged("imageHeight");}
}

您还需要在班级中实施INotifyPropertyChanged

 public class YourClassName : INotifyPropertyChanged //Hold control and hit period to add the using for this
    {

        PropertyChangedEventHandler PropertyChanged;
        void OnPropertyChanged(String prop){
           PropertyChangedEventHandler handler = PropertyChanged;

           if(handler!=null){
              PropertyChanged(this, new PropertyChangedEventArgs(prop));
           }
        }
    }

如果全部接线,您只需在获取值时设置imageWidth和imageHeight属性即可。它会在UI中自动更改它。