Image Source from C# XAML - xaml

I need to set Image Source from C#. I tried X:Name="headimg" but I could not find headimg in C#.
<StackPanel x:Name="Body">
<Image x:Name="headimg" Source="img/logo.png" Height="120" Width="130" HorizontalAlignment="Left"></Image>
</StackPanel>

Try this:
public void SetImage()
{
BitmapImage imge = new BitmapImage(new Uri("/Assets/Images/ImageName.png", UriKind.Relative));
headimg.Source=image.Source;
}

Related

WinRT / UWP: Loading RelativePanel with XamlReader causes XamlParseException with RelativePanels Attached Properties

I'm trying to use the XamlReader to parse a XAML File on during runtime. Unfortunately I get a XamlParseException when the XamlReader tries to read the Relative Attributes like RelativePanel.Below.
This is the Code to load the xaml file:
using System;
using System.IO;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Markup;
namespace TestProject.UWP.Views
{
public sealed partial class LoginPage : Page
{
public LoginPage()
{
this.InitializeComponent();
Loaded += OnLoaded;
}
private async void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
folder = await folder.GetFolderAsync("TestData");
var file = await folder.GetFileAsync("LoginControl.xaml");
var xaml = await FileIO.ReadTextAsync(file);
var content = (UserControl)XamlReader.Load(xaml);
this.Content = content;
}
}
}
And this the xaml file i try to read from the local content
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TestProject.UWP.Views"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="800"
d:DesignWidth="600">
<RelativePanel Background="LightGray">
<Border x:Name="logoBorder" BorderBrush="White" BorderThickness="0,0,0,1" Margin="30,30,30,10" Width="200" Height="60" Padding="0,0,0,5" RelativePanel.AlignLeftWithPanel="True" RelativePanel.AlignRightWithPanel="True" RelativePanel.AlignTopWithPanel="True" >
<Image Stretch="Uniform" Source="ms-appx:///Assets/Images/logo.png" Width="200" />
</Border>
<Image x:Name="userIcon" Source="ms-appx:///Assets/Images/usericon.png" Margin="30,10" RelativePanel.AlignHorizontalCenterWithPanel="True" RelativePanel.AlignRightWith="logoBorder" Width="100" Height="100"/>
</RelativePanel>
</UserControl>
When i try to parse the xaml i get the following Exception:
"WinRT information: RelativePanel error: Value must be of type UIElement."
As soon as i remove the attribute RelativePanel.AlignRightWith="logoBorder" from the second image everythings work fine.
Does someone has a idea to workaround this problem?
Edit:
Before you ask. The xaml should later be loaded from a server that's why i don't just instantiate a instance of the usercontrol in code.
Cheers
Kornelis
Replace the element name in
RelativePanel.AlignRightWith="logoBorder"
by an ElementName binding:
RelativePanel.AlignRightWith="{Binding ElementName=logoBorder}"

Pivot control header icon of un selected pivot in windows phone universal application

I have pivot control in my universal windows phone application. Defined like this
<PivotItem.Header>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Margin="0 0 10 0" Width="40" Source="/Assets/Images/cher.png" />
<TextBlock x:Uid="cherTextBlock" Grid.Column="1" Style="{StaticResource PivotHeadingStyle}" />
</Grid>
</PivotItem.Header>
When I am on first pivot the text of second pivot becomes dull. But offcourse the image doesn't become dull. I have same image with dull effect and I want that dul image to be shown when other pivot is shown.
One approach is that I make it programmatically and change the source of image when it is not in focus. But I want to know is that possible to do this in xaml or some other better approach than mine?
Accomplished it like programmatically
inside initialized component added this code
//RechargeAccountPivot is name of my pivot control.
RechargeAccountPivot.SelectionChanged += RechargeAccountPivot_SelectionChanged;
And this is selectionChanged event code. where i gave names to my all image controls and changed their icons.
private void RechargeAccountPivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (RechargeAccountPivot.SelectedIndex == 0)
{
PivotOneImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/Images/BalanceTopUpIcons/rechargeCard.png"));// new BitmapImage { UriSource = new Uri("//Assets/Images/BalanceTopUpIcons/rechargeCard.png") };
PivotTwoImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/Images/BalanceTopUpIcons/eVoucherDull.png"));
PivotThreeImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/Images/BalanceTopUpIcons/eVoucherDull.png"));
}
else if (RechargeAccountPivot.SelectedIndex == 1)
{
PivotOneImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/Images/BalanceTopUpIcons/rechargeCardDull.png"));
PivotTwoImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/Images/BalanceTopUpIcons/eVoucher.png"));
PivotThreeImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/Images/BalanceTopUpIcons/eVoucherDull.png"));
}
else
{
PivotOneImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/Images/BalanceTopUpIcons/rechargeCardDull.png"));
PivotTwoImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/Images/BalanceTopUpIcons/eVoucherDull.png"));
PivotThreeImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/Images/BalanceTopUpIcons/eVoucher.png"));
}
}

Search box implementation

I am developing my first app on windows phone 8. In this app I have a search box.For the search box I need to provide the background text as search city(as a hint text for the user) along with the search symbol/ search button within the box,Can I know the best way to do this as I am pretty new in this field.
Thanks in Advance.
Try this for watermark(hint text) on TextBox and search button at the top.
xaml
<Grid x:Name="ContentPanel" Grid.Row="0" Margin="12,0,12,0" Width="440" Height="100">
<TextBox Width="440" Name="txtSearch" Height="153" LostFocus="TextBox_LostFocus" GotFocus="TextBox_GotFocus" Text="This is whatever search..." TextWrapping="Wrap" Foreground="DarkGray" FontSize="18"></TextBox>
<Button x:Name="btnSearch" Click="btnSearch_Click" HorizontalAlignment="Right" Height="70" Margin="0,0,10,0">
<Button.Content>
<Image Source="Images/yoursearchIcon.png"></Image>
</Button.Content>
</Button>
</Grid>
code behind
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
if (txtSearch.Text.Trim() == "")
{
txtSearch.Foreground = new SolidColorBrush(Colors.DarkGray);
txtSearch.Text = "This is whatever search...";
}
}
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
if (txtSearch.Text == "This is whatever search...")
{
txtSearch.Foreground = new SolidColorBrush(Colors.Black);
txtSearch.Text = "";
}
}
Hope this helps
You could use the AutoCompleteBox where you could implement the search functionality too.
Have a look over here
http://www.geekchamp.com/articles/autocompletebox-for-wp7-in-depth
Hope it helps!

Image rotation as animation

I am making a Windows 8 application in visual studio 2012 c#.
I am having an image '1.png' and I want to rotate it at any angle as an animation along its center point.
But i want to do it with the help of c# code rather than XAML code.
Thank You in Advance.
In your XAML, have the following image:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Image Source="/Assets/Logo.png" Width="300" RenderTransformOrigin="0.5, 0.5">
<Image.RenderTransform>
<RotateTransform x:Name="rotateTransform"/>
</Image.RenderTransform>
</Image>
</Grid>
Then, in code, write the following when you want to animate (you create the Storyboard programmatically, then add to it a relevant Timeline. Note that you can also create the RotateTransform in code if you want.
async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
await Task.Delay(500);
Storyboard board = new Storyboard();
var timeline = new DoubleAnimationUsingKeyFrames();
Storyboard.SetTarget(timeline, rotateTransform);
Storyboard.SetTargetProperty(timeline, "Angle");
var frame = new EasingDoubleKeyFrame() { KeyTime = TimeSpan.FromSeconds(1), Value = 360, EasingFunction = new QuadraticEase() { EasingMode = EasingMode.EaseOut } };
timeline.KeyFrames.Add(frame);
board.Children.Add(timeline);
board.Begin();
}
This will rotate the object 360 degrees.
BTW: I am writing a set of posts that show an even better way of animating. It's not done yet, but it will give you a general idea on how to get a framework for certain types of animations..
First part of the series
Thanks Shahar! I took your example and made a custom control. It's actually an infinite spinning of one ring image.
Spinner.xaml:
<UserControl x:Class="MyControls.Spinner"
...
<Grid >
<Image Source="/Assets/Images/spinner.png" Width="194" RenderTransformOrigin="0.5, 0.5">
<Image.RenderTransform>
<RotateTransform x:Name="rotateTransform"/>
</Image.RenderTransform>
</Image>
</Grid>
</UserControl>
Spinner.cs:
namespace MyControls
{
public partial class Spinner: UserControl
{
public Spinner()
{
InitializeComponent();
this.Loaded += Spinner_Loaded;
}
private void PlayRotation()
{
Storyboard board = new Storyboard();
var timeline = new DoubleAnimationUsingKeyFrames();
Storyboard.SetTarget(timeline, rotateTransform);
Storyboard.SetTargetProperty(timeline, new PropertyPath("(Angle)"));
var frame = new EasingDoubleKeyFrame() { KeyTime = TimeSpan.FromSeconds(5), Value = 360, EasingFunction = new QuadraticEase() { EasingMode = EasingMode.EaseOut } };
timeline.KeyFrames.Add(frame);
board.Children.Add(timeline);
board.RepeatBehavior = RepeatBehavior.Forever;
board.Begin();
}
private async void Spinner_Loaded(object sender, RoutedEventArgs e)
{
PlayRotation();
}
}
}
Then when you want to use Spinner in another xaml, it's very simple:
Just add a line for it inside any Grid etc:
<include:Spinner/>
(of course you need to define include as something like:
xmlns:include="MyControls"
on top of your xaml)

Code behind works but MVVM doesnt

I have been messing with something that works in the code behind but when I try and bind to a MVVM , nothing displays. First I will show the code behind, then MVVM ( same xaml ). I want to use MVVM and not code behind.
Code Behind (works):
var loadOp = ctx.Load<GateBlox.Web.Models.Structure>(ctx.GetStructuresQuery());
loadOp.Completed += (s, e) => { _treeView.ItemsSource = loadOp.Entities.Where(struc => !struc.StructureParentFK.HasValue); };
XAML
<Grid x:Name="LayoutRoot">
<sdk:TreeView x:Name='_treeView' DataContext='{StaticResource ViewModel}'>
<sdk:TreeView.ItemTemplate>
<sdk:HierarchicalDataTemplate ItemsSource='{Binding Children}'>
<TextBlock Text='{Binding StructureName}' />
</sdk:HierarchicalDataTemplate>
</sdk:TreeView.ItemTemplate>
</sdk:TreeView>
</Grid>
MVVM (doesnt bind)
private LoadOperation<Structure> _loadStructures;
private StructureContext _structureContext;
private IEnumerable<Structure> _structures;
public IEnumerable<Structure> Structures
{
get { return this._structures; }
set { this._structures = value; RaisePropertyChanged("Structures"); }
}
public StructuresViewModel()
{
if (!DesignerProperties.IsInDesignTool)
{
_structureContext = new StructureContext();
_loadStructures = _structureContext.Load(_structureContext.GetStructuresQuery().Where (p=> ! p.StructureParentFK.HasValue));
_loadStructures.Completed += new EventHandler(_loadStructures_Completed);
}
}
void _loadStructures_Completed(object sender, EventArgs e)
{
this.Structures = _loadStructures.Entities;
}
Have your checked that you are not getting a binding expression error in the output? You are binding the items source of the data template to a property named Children, but your view model exposes a data source named Structures.
Also, in your working example, you are setting the ItemsSource of the TreeView, but in your MVVM XAML you are setting the ItemsSource of your data template. Is there an inconsistency between what ItemsSource you need to set/bind to?
You might also consider using a collection data source that implements the INotifyCollectionChanged interface (ObservableCollection or expose the binding source as a ICollectionView that uses a PagedCollectionView).
I recommend you take a look at this information about data binding in MVVM, as it provides excellent guidance on setting up data sources in your view models.
You are not setting the ItemsSource for your TreeView. I think your xaml should look something like this:
<Grid x:Name="LayoutRoot">
<sdk:TreeView x:Name='_treeView' DataContext='{StaticResource ViewModel}'
ItemsSource="{Binding Structures}">
<sdk:TreeView.ItemTemplate>
<sdk:HierarchicalDataTemplate ItemsSource='{Binding Children}'>
<TextBlock Text='{Binding StructureName}' />
</sdk:HierarchicalDataTemplate>
</sdk:TreeView.ItemTemplate>
</sdk:TreeView>
</Grid>
Hope this helps :)
I almost have it working now. I took a different approach and went with a HeirarchicalDataTemplate. At the moment the data is showing but not correctly: The child1 record is shwoing up as a parent as well.
Parent1(level1)
Parent2(level1)
Child1(level2)
Child1(level1)
<navigation:Page x:Class="GateBlox.Views.Structure"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
d:DesignWidth="640"
d:DesignHeight="480"
Title="Structure Page"
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
xmlns:viewmodel="clr-namespace:GateBlox.ViewModels">
<UserControl.Resources>
<viewmodel:StructuresViewModel x:Key='ViewModel'>
</viewmodel:StructuresViewModel>
</UserControl.Resources>
<Grid x:Name="LayoutRoot"
DataContext='{StaticResource ViewModel}'>
<Grid.Resources>
<sdk:HierarchicalDataTemplate x:Key="ChildTemplate"
ItemsSource="{Binding Path=Parent}">
<TextBlock FontStyle="Italic"
Text="{Binding Path=StructureName}" />
</sdk:HierarchicalDataTemplate>
<sdk:HierarchicalDataTemplate x:Key="NameTemplate"
ItemsSource="{Binding Path=Children}"
ItemTemplate="{StaticResource ChildTemplate}">
<TextBlock Text="{Binding Path=StructureName}"
FontWeight="Bold" />
</sdk:HierarchicalDataTemplate>
</Grid.Resources>
<sdk:TreeView x:Name='treeView'
Width='400'
Height='300'
ItemsSource='{Binding Structures}'
ItemTemplate='{StaticResource NameTemplate}'>
</sdk:TreeView>
</Grid>
using System;
using System.Collections.ObjectModel;
using GateBlox.Web.Models;
using System.ServiceModel.DomainServices.Client;
using GateBlox.Web.Services;
using GateBlox.Helpers;
using System.ComponentModel;
using System.Collections.Generic;
namespace GateBlox.ViewModels
{
public class StructuresViewModel : ViewModelBase
{
private LoadOperation<Structure> _loadStructures;
private StructureContext _structureContext;
private ObservableCollection<Structure> _structures;
public ObservableCollection<Structure> Structures
{
get { return this._structures; }
set { this._structures = value; RaisePropertyChanged("Structures"); }
}
public StructuresViewModel()
{
if (!DesignerProperties.IsInDesignTool)
{
_structureContext = new StructureContext();
_loadStructures = _structureContext.Load(_structureContext.GetStructuresQuery());
_loadStructures.Completed += new EventHandler(_loadStructures_Completed);
}
}
void _loadStructures_Completed(object sender, EventArgs e)
{
this.Structures = IEnumerableConverter.ToObservableCollection(_loadStructures.Entities);
}
}
}