WP7 change a button image in code with a url - windows-phone-7

Set a button's background is not as simple as android's dev.it's more complex;
in .xaml file:
<Button Click="Button_Click" x:Name="img_btn">
<Button.Template>
<ControlTemplate>
<!--set button background that we can hanle click event-->
<Image HorizontalAlignment="Left" Margin="0,-69,0,479" x:Name="image1" Stretch="Fill" Width="480" Source="/myNameSpace;component/home_003.jpg" />
</ControlTemplate>
</Button.Template>
</Button>
in this .cs file:
JsonObject jsonObject = (JsonObject)JsonObject.Load(e.Result);
ads_address = jsonObject["imageurl"];//get a url from jsonobject
ImageBrush imageBrush = new ImageBrush();
imageBrush.ImageSource = new BitmapImage(new Uri(ads_address));//ads url likes //"http://27.98.194.93/forum/images/2009/home_004.jpg";
this.img_btn.Background = imageBrush;//this code is not work,perhaps, I can't get what I want(Image) with code "this.img_btn.Background"
how can I get this Image in Button.If can't what's the way to set a button background with a url in code;

try this
Create image source at first and then giving that source to the image control you are using.
string imagepath = "url";
ImageSource imgsrc1 = new BitmapImage(new Uri(imagepath, UriKind.RelativeOrAbsolute));
//image can be Image/ImageBrush
image.Source = imgsrc1;

Related

UWP XAML ImageBrush.imageSource from networkshare

i edited my question:
i have a stack panel with buttons from array.
now I want to set the Button Background from networkshare images.
here ist my source code:
XAML:
<Page
x:Class="App4.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App4"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Height="1205.722" Width="2045.722">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Margin="0,0,0,0">
<StackPanel x:Name="sp" HorizontalAlignment="Left" Height="1070" Margin="10,10,0,0" VerticalAlignment="Top" Width="145" Padding="0" CornerRadius="10" RequestedTheme="Light" ScrollViewer.HorizontalScrollBarVisibility="Visible" Grid.RowSpan="2">
<FlyoutBase.AttachedFlyout>
<MenuFlyout/>
</FlyoutBase.AttachedFlyout>
</StackPanel>
</Grid>
Behind Code:
private void onLoad()
{
for (int i = 0; i < imgNames.Length; ++i)
{
ImageBrush brush1 = new ImageBrush();
brush1.ImageSource = new BitmapImage(new Uri("ms-appx:///assets/" + imgNames[i]));
Button button = new Button()
{
Content = string.Format(""),
Tag = i
};
button.Width = 100;
button.Height = 100;
button.Background = brush1;
button.Margin = new Thickness(0, 20, 0, 0);
button.Click += new RoutedEventHandler(button_Click);
this.sp.Children.Add(button);
}
}
Thanks
For loading image from network source you need to use these capabilities in your app
<Capabilities>
<Capability Name="internetClient" />
<Capability Name="privateNetworkClientServer" />
<Capability Name="internetClientServer" />
<uap:Capability Name="enterpriseAuthentication" />
</Capabilities>
and your image
<Image Name="YourImageElementName" />
and loading image in code behind
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(#"\\Your Image Full Path e.g user\folder\subfolder");
StorageFile file = await folder.GetFileAsync("ImageName.jpg");
using (var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(stream);
YourImageElementName.Source = bitmap;
}
Github sample i created for this https://github.com/shubdragon/LoadNetworkImageRepo
Points need to noted
1) You need to set your network location in code and image name with required extension.
2) must share that location to homegroup.
3) Note code behind in different pages and Package.appxmanifes (view it as code in xml editor)

how to arrange two images side by side in list view in windows phone RT app

I am developing windows phone app,in this app I want to arrange two images side by side using list view control. Actually what happend is I am binding images in listview ,but images are binding one image below another image was binding . how to arrange images side by side in listview and how to set width of the image in all the resolution screens.please help me.
Below is my sample code.
<ListView x:Name="listviewfreecredits" Margin="0,-1,0.643,10" Height="521" IsItemClickEnabled="True" ItemClick="listviewfreecredits_ItemClick">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel >
<Grid Margin="10,10,50,10" Width="389" >
<Image Source="{Binding DealImage}" Stretch="None" Width="400" Height="300" />
</Grid>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
string result = "";
HttpWebRequest request = HttpWebRequest.Create(Url.weburl + "FreeCredits_v2?PlatFormID=7") as HttpWebRequest;
request.Method = "GET";
WebResponse response = await request.GetResponseAsync();
using (var reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
// Do anything with you content. Convert it to xml, json or anything.
}
JObject jobj = JObject.Parse(result);
JArray jarr = (JArray)jobj["Deals"];
if (jarr != null)
{
for (int i = 0; i < jarr.Count; i++)
{
string DealImage = (string)jarr[i]["DealImage"];
string DealID = (string)jarr[i]["DealID"];
string Buttontext = (string)jarr[i]["Buttontext"];
freecredit obj = new freecredit();
obj.DealImage = Url.imgurl + DealImage;
obj.DealID = DealID;
obj.ButtonText = Buttontext;
this.listviewfreecredits.Items.Add(obj);
}
Use GridView control instead of ListView, and for width for each image you can calculate it and bind width and height and height of the image in your image control. e.g.
<GridView x:Name="listviewfreecredits" Margin="0,-1,0.643,10" Height="521" IsItemClickEnabled="True" ItemClick="listviewfreecredits_ItemClick">
<GridView.ItemTemplate>
<DataTemplate>
<StackPanel >
<Grid Margin="10,10,50,10" Width="389" >
<Image Source="{Binding DealImage}" Stretch="None" Width="{Bind ImageWidth}" Height="{Bind ImageWidth}" />
</Grid>
</StackPanel>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
for (int i = 0; i < jarr.Count; i++)
{
string DealImage = (string)jarr[i]["DealImage"];
string DealID = (string)jarr[i]["DealID"];
string Buttontext = (string)jarr[i]["Buttontext"];
freecredit obj = new freecredit();
obj.DealImage = Url.imgurl + DealImage;
obj.DealID = DealID;
obj.ButtonText = Buttontext;
//set image width, height by calculating with height accordingly
obj.ImageWidth = ((Windows.UI.Xaml.Window.Current.Bounds.Width - 50/ 2);
this.listviewfreecredits.Items.Add(obj);
}
Define ImageWidth property as double in your freecredit class

How to fill a rectangle with an image that is coming from a bound listbox on event fire in WP7

i want to create a greeting card maker app for WP7, when a user double taps an image from a listbox, I want that selected image to fill a rectangle on the same page.
Im passing 50 images into the list box like this:
public GCM()
{
InitializeComponent();
var articles = new List<Article>();
for (byte i = 1; i <= 20; i++)
{
Article article = new Article() { Name = "name"+i, ImagePath = "Assets/Images/Backgrounds/"+i+".jpg" };
articles.Add(article);
}
listBox1.DataContext = articles;
}
and its working fine, now heres an xml snippet:
<Rectangle Fill="#FFF4F4F5" Margin="28,24,30,148" Stroke="Black" Name="rect1" />
................(more code here).........................
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="10" >
<Image Name="bgs" Source="{Binding ImagePath}" Height="90" Width="90" DoubleTap="Load_BG" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
how can i fill the rectangle with the tapped image? this code (below) sets the string null everytime, no matter which image i select, although to my knowledge each has a different name and it should give different names for different images. I will use the name of the image to fill the rectangle. What am i doing wrong?
private void Load_BG(object sender, System.Windows.Input.GestureEventArgs e)
{
string abc = sender.GetType().Name;
}
Please excuse me if the solution is obvious..this is my first app ever. Thank you!
sender parameter should contains the control that triggered the event, in this case Image control. Try to cast it to Image type, then you can get the information you needed from Source property :
private void Load_BG(object sender, System.Windows.Input.GestureEventArgs e)
{
Image img = (Image)sender;
//do something with img.Source here
}
so heres the solution, it works now :)
private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var img = listBox1.SelectedItem as Article;
ImageBrush imgBrush = new ImageBrush();
imgBrush.ImageSource = new BitmapImage(new Uri(img.ImagePath, UriKind.RelativeOrAbsolute));
rect1.Fill = imgBrush;
}

Want to set storyboard target property as horizontal offset of a scrollviewer

I am using scroll viewer in my app which shows images in a horizontal view. I need to use animation while scrolling like in this video how to acheive this
http://www.youtube.com/watch?v=XVHVBMeqL24
I have tried this
public Storyboard CreateAndApplyStoryboard(UIElement targetElement)
{
Storyboard sb = new Storyboard();
DoubleAnimation animation =
new DoubleAnimation { From = 0, To = 500, Duration = new Duration(TimeSpan.FromSeconds(1.0)) };
//ExponentialEase ese = new ExponentialEase();
//ese.EasingMode = EasingMode.EaseIn;
//animation.EasingFunction = ese;
Storyboard.SetTarget(animation, targetElement);
Storyboard.SetTargetProperty(animation,
new PropertyPath(ScrollViewer.HorizontalOffsetProperty));
sb.Children.Add(animation);
return sb;
}
I am just showing the example i need to scroll from horizontal offset 0 to 500
How to use the dependency property?
<scrollviewer name="scroll">
<StackPanel Name="stack" Width="5000" Orientation="Horizontal" HorizontalAlignment="Left" >
<StackPanel.RenderTransform>
<TranslateTransform x:Name="Trans2" X="0" Y="0" />
</StackPanel.RenderTransform>
</StackPanel>
private void button1_Click(object sender, RoutedEventArgs e)
{
Storyboard sb = CreateAndApplyStoryboard(scroll);
sb.Begin();
}

view gif image in image UI control windows phone 7

I want to display the gif image in the UI image control.
I have Image image1;
image1.source = new BitmapImage(new Uri(link, UriKind.Absolute));
but the link in Uri is a .gif image.
I have read this: imagetool however I still not get it how to use the library. I did download the library and add references, then from that I'm stuck, I want to set source in code.
Can you help explains it a little bit more?
My code currently like this:
<UserControl.Resources>
<imagetools:ImageConverter x:Key="ImageConverter" />
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid HorizontalAlignment="Right" Width="69">
<Border BorderBrush="White" BorderThickness="3" CornerRadius="7" Background="Black">
<Image Width="69" Height="69" Name="canvasImage" Stretch="UniformToFill" HorizontalAlignment="Center" VerticalAlignment="Center" ImageFailed="canvasImage_ImageFailed" />
</Border>
<Border BorderBrush="White" BorderThickness="3" CornerRadius="7" Background="Black">
<imagetools:AnimatedImage Name="canvasGifImage" Width="69" Height="69" Stretch="UniformToFill" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
</Grid>
</Grid>
In my MainPage.xaml.cs, because I don't know whether it is an png/jpg or a gif, so I have it try to load png/jpg first, if failed then try load gif in the imagetools control name canvasGifImage:
private void DisplayImage(int index, string link)
{
try
{
control1.canvasImage.Source = new BitmapImage(new Uri(link, UriKind.Absolute));
}
catch //if fail to load image as normal, do this
{
//but I dont know how to set Source for the canvasGifImage, help me here:
control1.canvasGifImage.Source = *new BitmapImage(new Uri(link, UriKind.Absolute));*
}
}
Replace the use of the ManualResetEvent for async code.
using (var resetEvent = new ManualResetEvent(false))
{
ImageTools.IO.Decoders.AddDecoder<GifDecoder>();
var extendedImage = new ExtendedImage();
extendedImage.LoadingCompleted += (s, e) => resetEvent.Set();
extendedImage.LoadingFailed += (s, e) => resetEvent.Set();
extendedImage.SetSource(gifStream);
resetEvent.WaitOne(TimeSpan.FromSeconds(5));
// Check for timeout or error
var enc = new JpegEncoder();
var jpegStream = new MemoryStream();
enc.Encode(extendedImage, jpegStream);
...
}

Resources