繁体   English   中英

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

[英]Set Image width and height at runtime

我正在Windows Phone 8应用程序上工作。

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

列表框数据模板

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

为了获得图像的宽度和高度,我使用此代码

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
}

但是如何更改宽度和高度并进行设置?

将width和height属性添加到您的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属性。 它将在用户界面中自动更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM