【问题标题】:Set Image width and height at runtime在运行时设置图像宽度和高度
【发布时间】:2014-05-08 14:37:54
【问题描述】:

我正在开发 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 属性并从 Image 对象绑定到它们,类似于绑定到 ImageName 的方式。
  • @igrali 你能给我举个例子吗

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


【解决方案1】:

将宽度和高度属性添加到您的 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 中自动更改。

【讨论】:

猜你喜欢
  • 2012-03-01
  • 2014-06-21
  • 2016-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-26
相关资源
最近更新 更多