Showing posts with label XAML. Show all posts
Showing posts with label XAML. Show all posts

Sunday, January 18, 2015

Working in designtime with Data in MVVM

If we develop applications ( XAML based) we have a problem with see the data in design view. Every application become successful when its interface is attractive. If our application is based on internet or any other computational task there is difficulty on make Interfaces without running the application real time. Here is solution for it

Use design time data binding which already with the xaml based application 

Today we going to develop the windows 8.1 store application. ( This is same with any XAML based Application )

1. Create Windows 8.1 store application form the Visual studio. (I named it as DesignTimedata )
2. Create ViewModel to bind the run time data , In following here is My MainViewModel.cs

With this example we are not going to the use internet or other tasks .therefore just hard corded the values in constructor 

namespace DesignTimeData.Runtime
{
    public class MainViewModel:INotifyPropertyChanged
    {
 
        private string _Title { getset; }
        public string Title
        {
            get { return _Title; }
            set
            {
                _Title = value;
                OnPropertyChanged("Title");
            }
        }
 
        private string _Description { getset; }
        public string Description
        {
            get { return _Description; }
            set
            {
                _Description = value;
                OnPropertyChanged("Description");
            }
        }
 
 
 
        public MainViewModel()
        {
        // Hard coded runtime data
            this._Title = "Title in Run time";
            this._Description = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.";
        }
 
        // Create the OnPropertyChanged method to raise the event 
        // Use in MVVM
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(thisnew PropertyChangedEventArgs(name));
            }
        }
    }
}


2. Then bind the ViewModel to the View with relevant tags.
You can use Singleton or Page Resource binding . In here Im using Bind the ViewModel to the Page in XAML . It gives me intellisense in XAML .

Here is my MainPage.xaml

<Page
    x:Class="DesignTimeData.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:DesignTimeData"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:runtime="using:DesignTimeData.Runtime"
    mc:Ignorable="d">
    
    <Page.DataContext>
        <runtime:MainViewModel/>
    </Page.DataContext>
 
3 .Then Create New Class which have exact name of your view model. Better to use different namespace / folder . In this case It is MainViewModel 
Here is my design time ViewModel. It will contains all test data which displayed in design view in visual studio


namespace DesignTimeData.DesignTimedata
{
    public class MainViewModel
    {
        public string Title { get { return "DesignTime Title"; } }
 
        public string Description { get { return "Design time description"; } }
    }
} 

4. Then lets bind the design time data into the design (xaml) . In here there is always tag like this
      mc:Ignorable="d" 
with every page. something defines under this tag will not be displayed in the runtime. then this is the one that we need to use.

With this d we can define all the properties which page have and change them. but none of them are effecting the real application .

Lets bind the ViewModel to the page and use it with design time . Here is my full page

<Page
    x:Class="DesignTimeData.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:DesignTimeData"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:desgn="using:DesignTimeData.DesignTimedata"
    xmlns:runtime="using:DesignTimeData.Runtime"
    mc:Ignorable="d">
    
    <Page.DataContext>
        <runtime:MainViewModel/>
    </Page.DataContext>
    
    <d:Page.DataContext>
        <desgn:MainViewModel />
    </d:Page.DataContext>
    
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel Margin="100,150,0,0">
            <TextBlock Style="{StaticResource HeaderTextBlockStyle}" Text="{Binding Title}"/>
            <TextBlock Style="{StaticResource SubtitleTextBlockStyle}" Text="{Binding Description}"/>
        </StackPanel>
    </Grid>
</Page>

Now we can see the vaues that we put to test the Application UI and make any changes to it.














Here is runtime result of the app















Enjoy







Full Code 
http://bit.ly/1xiJ3yZ

 

Monday, July 7, 2014

Code Optimization with LINQ

What is LINQ ?
Language-Integrated Query (LINQ) is a set of features introduced in Visual Studio 2008 that extends powerful query capabilities to the language syntax of C# and Visual Basic. LINQ introduces standard, easily-learned patterns for querying and updating data, and the technology can be extended to support potentially any kind of data store. Visual Studio includes LINQ provider assemblies that enable the use of LINQ with .NET Framework collections, SQL Server databases, ADO.NET Datasets, and XML documents.
(Definition from : msdn)

LINQ With If  Else

//LINQ conditional If
            //if text in textBox1 is a pop up message that found A else pop up not A
            //Usual code
            //if (textBox1.Text.Equals("A"))
            //{
            //    MessageBox.Show("Found 'A'");
            //}
            //else
            //{
            //    MessageBox.Show("Not 'A'");
            //}
            var d = textBox1.Text.Equals("A") ? MessageBox.Show("Found 'A'") :MessageBox.Show("Not 'A'");

With LINQ simple If Else condition is just single line code. isn't it amazing

Getting Elements from User Interface

My interface has four TextBoxes and I need to popup every Textboxe's Text where it strts from 'A' letter.














//Add all items starts with 'A' to List
            var  selectedBoxes = MainGrid.Children.OfType<TextBox>().Where(x=> x.Text.StartsWith("A")).ToList();
            //pop up them
            foreach (var item in selectedBoxes)
            {
                MessageBox.Show(item.Text);
            }


Like this you can traverse any Collection on C# and filter.

And simply Order the elements in Collections with Order By function in LINQ

var  selectedBoxes = MainGrid.Children.OfType<TextBox>().Where(x=> x.Text.StartsWith("A")).OrderBy(x=> x.Text).ToList();

Select
 Just take each of Dealer contract and dealer as two tables in DB

var dealerContracts = DealerContact.Join(Dealer,
                                 contact => contact.DealerId,
                                 dealer => dealer.DealerId,
                                 (contact, dealer) => contact);





Enjoy...




Sunday, July 6, 2014

Making animations In Store Apps

With the application development with XAML is little bit complex with user interface need animations , no matter which kind of application you gonna build. 

This post will demonstrate about how to make simple animation with XAML application with the help of Blend for Visual Studio(Former Microsoft Expression Blend). With visual studio 2012 onwards Blend for Visual Studio is free tool that installed with the Visual Studio.

1. Create your XAML based application in Visual Studio  (It may be WPF, Windows Phone or Windows Store App).
2. Open XAML interface in Design View and add relevant controllers to it. In here we just adding rectangle and we are going to create animation that  rectangle moves and rotate 360 degrees.
3. Select XAML (.xaml) file in  Solution Explorer and select Open in Blend Option























Here how its look like

4. Then select the rectangle and click on the  (+) button on the Object and Timeline window and add name to the animation (Storyboard) in here we named it as animationDemo

5. Now you can see the interface like the timeline.








6. Select the object you need to animate. this time its rectangle. then hold the Yellow color line on the timeline and drag it to the time period you need to appear the animation. (Ex : 5 msec) then drop it and make the changes that you need to  do within that time period to the object.





















7. Then play it using play button and check the animation is done. and Save.
8. but not yet over. even animation created its not playing while the application run time. To do that go to code behind and place that where you need to play the animation . This case it need to play on the start.
go to place  where animation need to play  and paste this code .
animationDemo.Begin();


then You are done with it. See the code behind the XAML page. Blend does some serious codeing for you, in this case it like this.

<Storyboard x:Name="animationDemo">
            <DoubleAnimation Duration="0:0:5" To="767.164" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateX)" Storyboard.TargetName="rectangle" d:IsOptimized="True"/>
            <DoubleAnimation Duration="0:0:5" To="-10.448" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateY)" Storyboard.TargetName="rectangle" d:IsOptimized="True"/>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.Rotation)" Storyboard.TargetName="rectangle">
                <EasingDoubleKeyFrame KeyTime="0:0:5" Value="0"/>
                <EasingDoubleKeyFrame KeyTime="0:0:10" Value="219.832"/>
            </DoubleAnimationUsingKeyFrames>
        </Storyboard>









Full Code In Media Fire 
http://bit.ly/blendDemo