Question

I am working on windows phone 8 app.

i have list box with image and value binded to it.I need to set the width and height of the image before its being display.

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

To get the width and height of Image i use this code

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
}

But how to change the width and height and set it ?

Was it helpful?

Solution

Add the width and height properties to your 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}"
/>

In your backend code you need to create the two properties that you are binding too.

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");}
}

You will also need to have INotifyPropertyChanged implemented in your class

 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));
           }
        }
    }

When this is all wired up all you have to do is set the imageWidth and imageHeight properties when you get the values. It will automatically change it in the UI.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top