[英]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.