Showing posts with label Silverlight. Show all posts
Showing posts with label Silverlight. Show all posts

Thursday, September 16, 2010

Enable scroll in a disabled ListBox in Silverlight

Sometimes we get a requirement that asks to enable scrolling on a long ListBox control while keeping its content disabled. The easy workaround for this is to wrap the ListBox with ScrollViewer control in Silverlight.

 

If you hide the border of ListBox and set the padding of ScrollViewer to zero, then the difference as compared to normal ListBox is unnoticeable e.g. see below

imageHere the XAML

<ScrollViewer VerticalScrollBarVisibility="Auto" Height="100" Width="110" Padding="0">
            <ListBox x:Name="lstCities" ItemsSource="{Binding}" ScrollViewer.VerticalScrollBarVisibility="Hidden" BorderThickness="0" IsEnabled="False">
            <ListBox.ItemTemplate>
                <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <CheckBox></CheckBox>
                            <TextBlock Text="{Binding Name}"></TextBlock>
                        </StackPanel>                        
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        </ScrollViewer>


Technorati Tags: ,


LiveJournal Tags:

Wednesday, July 9, 2008

Differences between WPF and Silverlight

Nowadays, two terms are mostly heard in Windows Graphics sphere, WPF and Silverlight. Many of us presume they are one and the same thing. But actually there are fundamental differences between the two. In this post, I'm posting the basic differences between the two (primarily Silverlight 1.x)
WPFSilverlight 1.x
WPF is the complete graphics framework written from the scratch by MicrosoftSilverlight is subset of WPF in the sense that it contains only windows independent class libraries of WPF
WPF applications are not Web enabled. They are mostly focused around Windows FormsSilverlight has been introduced for the sole purpose of enabling Web support for WPF applications
WPF applications are supported by only Windows based computersSilverlight provides support for different browsers like Firefox and Safari
WPF applications whole heartily support and use C#Silverlight applications use XAML and Javascript to define their markup and behaviour. C# code is not supported
WPF requires .NET runtimeSilverlight doesn't require .NET runtime to render its graphics
WPF uses Windows media player on the client to play any mediaSilverlight uses OS media support to play media
WPF has capability to create 3D graphicsSilverlight is limited to 2D graphics only

Silverlight HyperlinkButton turns page blank

Today when I was using the HyperlinkButton control on a Silverlight page and supplying it proper values for NavigateUri and Content attributes, I found that the control was not behaving properly and made the page blank while rendering in the browser.

It threw browser exception saying InvalidOperationException. This was the code which I was using

<HyperlinkButton x:Name=”lnkSports” Content="Sports Page"

NavigateUri="http://easports.com" Grid.Row="0" Grid.Column="1"/>

It happens because HyperlinkButton expects its NavigateUri property to be of type System.Uri rather than System.String


lnkSports.NavigateUri=new Uri("http://easports.com");

So a simple creation of Uri object in the code behind helped to solve this problem as shown above

Handle Silverlight event in javascript

This post will show you how to throw events from Silverlight controls in managed code and catch them in javascript. Such a scenario comes while building HTML bridge in Beta 2, when you need to catch the events from Silverlight UserControls in the aspx page hosting them. We'll take the example of ListBox SelectionChanged Event. Whenever Listbox's selection is changed in the SL user control we'll show an alert on javascript which is having that SelectedText from the Listbox. Firstly the UserControl say UserControl1 which will throw the event, needs to have an event and a property marked with ScriptableMemberAttribute which is found under System.Windows.Browser. So here is how you add Scriptable members

private string _selectedText;
[ScriptableMemberAttribute]
public string SelectedText{
get{
return _selectedText;
}
}
[ScriptableMemberAttribute]
public event EventHandler MySelectionChanged;



Then we'll add the code the update the SelectedText property whenever ListBox selection is changed



private void lstMaster_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
_selectedText= lstMaster.SelectedItem.ToString();
if (MySelectionChanged != null)
{
MySelectionChanged(sender,e);
}
}



The above code also raises the event which will be caught in JS

After this you need to register UserControl1 in the App.xaml file so that it available to the host aspx page's javascript. This is code you need to write for that

private void Application_Startup(object sender, StartupEventArgs e)
{
UserControl1 objPage = new UserControl1();
HtmlPage.RegisterScriptableObject("registerPage", objPage);
}


Then finally we'll register an event handler for our custom event to a javascript method. This is done by on the OnPluginLoaded attribute of the <asp:Silverlight> control tag. Here's the code for that


//Adding javascript event listener
function hookEvent(sender){
var UC=sender.get_element();
UC.Content.registerPage.addEventListener("MySelectionChanged",jsEventHandler);
}

function jsEventHandler(sender,args){
var UC=document.getElementById("Xaml1");
alert( UC.Content.registerPage.SelectedText);
}



Essential XAML Simplified 2

As we have seen in the previous post XAML provides new generation of opportunities by which we can describe an object. Here we'll cover the remaining two concepts

  • Attached Properties
  • Markup Extensions

Going back to previous example of TextBlock which is shown below

<TextBlock Text="Title:" Style="{StaticResource TextBlockStyle}"

Grid.Row="0" Grid.Column="0" HorizontalAlignment="Right"></TextBlock>

Attached Properties refers to the ability by which child objects can set properties of parent object. In this control Grid (parent control) contains this TextBlock (child control). The way it helps is child elements inform the parent element of how they are to be presented in the user interface (UI). Another possiblity is different child elements unique values for the same parent element depending their own suitability. A point not be missed here is that a control which sports Attached Properties should implement them as Dependency properties in it own definition.

Alright! Markup Extensions.

Basically it refers to the attribute value being picked up from a collection which is described elsewhere. In the above example the Collection of StaticResource(s) can be put inside App.xaml (which is common markup for all your applications in the assembly) like this

<Application.Resources>

<Style x:Key="TextBlockStyle" TargetType="TextBlock">

<Setter Property="ForeGround" Value="Black"></Setter>

<Setter Property="Margin" Value="2"></Setter>

</Style></Application.Resources>

Similar we can have a Binding Markup like

Text="{Binding QuantityOnHand}"

where QuantityOnHand is column in an IEnumerable collection.

Monday, July 7, 2008

ProtocolException 404 Silverlight WCF

This is blog entry will help those who understand Cross Domain restrictions in Silverlight while calling a WCF service in another domain. If you already tried many prescribed things to allow Cross Domain Access like placing the clientaccesspolicy.xml in wwwroot folder and putting a crossdomain.xml on the IIS root (wwwroot folder). But still you are getting the same obstinate 404 error. Then you can try these two tricks which worked for me

1. Firstly make sure the you restart IIS whenever you create new policy files or update them.

2. Make sure that you SL client is an aspx page not HTML page (because aspx page runs in worker process account, somehow html doesn't work for some people)

3. Try changing this line in your clientaccesspolicy.xml

From :

<allow-from>
<domain uri="*"/>
</allow-from>

To:

<allow-from http-request-headers="*">
<domain uri="*"/>
</allow-from>

These tricks worked for me and I wish they work for you also :)

Wednesday, July 2, 2008

Adding multiple Silverlight user controls on aspx

Sometimes we have requirement of adding multiple Silverlight UserControls over same ASP.NET web page (aspx). Like when you want to host silverlight web parts on a single aspx page in separate areas.
All silverlight controls are zipped into a single .xap file. And the tag refers to xap file using source attribute as shown in the below code
<asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/MySLapp.xap" />
The App.xaml file contains the Application_Startup event which contains the information about the starting user control which will be rendered when the silverlight xaml is consumed by the browser. We can manipulate the InitParams property of this method to dynamically set the starting user control for the silverlight application. The below method shows how can we achieve the requirement of calling different user controls from the same aspx page.

Firstly set the different user controls on the aspx page as shown below

<asp:Silverlight ID="Xaml1" InitParameters="ControlId=1" runat="server" Source="~/ClientBin/MySLapp.xap" />
<asp:Silverlight ID="Xaml2" InitParameters="ControlId=2" runat="server" Source="~/ClientBin/MySLapp.xap" />
Next, you can dynamically set the user control to be rendered by the application using this logic
private void Application_Startup(object sender, StartupEventArgs e)
{
if (e.InitParams.ContainsKey("ControlId"))
{
if (e.InitParams["ControlId"] == "1" )
this.RootVisual = new UserControl1();
else
this.RootVisual = new UserControl2();
}
}

where UserControl1 and UserControl are you Silverlight UserControls.



InitializeFromXaml & XamlReader.Load in Silverlight Beta 2

In this post, we’ll discuss how to resolve two common issues which come while migrating Silverlight Beta 1 Apps to Beta 2. Below I am showing Beta 1 code and its equivalent code in Beta 2
Compile time error1. Does not contain a definition for InitializeFromXaml


//Beta 1
System.IO.Stream s = this.GetType().Assembly.GetManifestResourceStream("MyNamespace.UserControl1.xaml");
FrameworkElement control = this.InitializeFromXaml(new System.IO.StreamReader(s).ReadToEnd());



//Beta 2
Application.LoadComponent(control, new Uri("
;component/.xaml", UriKind.Relative));

OR


//Beta 2
System.IO.Stream s = this.GetType().Assembly.GetManifestResourceStream("MyNamespace.UserControl1.xaml");
FrameworkElement control = XamlReader.Load(new System.IO.StreamReader(s).ReadToEnd()) as Control;

Please note that <projectname> should be replaced by the VS 2008 project name or assembly dll name. component is a constant word and <classname> should be replaced by your .NET Class name of the User Control

Compile time error
2. No overload for method Load takes 2 arguments


//Beta 1
XamlReader.Load(string,boolean)

This function parses a well-formed XAML fragment and creates a corresponding Silverlight object tree, and returns the root of the object tree.


//Beta 2
XamlReader.Load(string)

Monday, June 9, 2008

Essential XAML Simplified 1

Today we'll touch the three most lauded concepts introduced by the XAML (eXtensible Application Markup Language). XAML to me seems like XML + .NET. By that I mean XAML provides you the best of both worlds by leveraging descriptive nature of XML and object-oriented nature of .NET. It allows you to instantiate a .NET object like WatermarkedTextbox and describe it properties using pure XML driven syntax, and all that in the Markup. So lets go ahead and explore these three majestic Xaml concepts :

  1. Property Element Syntax
  2. Attached Properties
  3. Markup Extensions

Property Element Syntax

Basically in XAML markup we have three types of element syntaxes

  • Object Element Syntax
  • Attribute Element Syntax
  • Property Element Syntax

To understand them one by one, lets take an example of the a simple WPF control, the TextBlock

<TextBlock Text="Title:" Style="{StaticResource TextBlockStyle}"

Grid.Row="0" Grid.Column="0" HorizontalAlignment="Right"></TextBlock>

Object element syntax refers to the way we have instantiated a .NET object ie TextBlock. Attribute element syntax means to how have used XML attributes (like HorizontalAlignment above) to define that object's properties and given it a value (ie Right). Now assume for a while that we have a TextBlock that displays a custom drawing instead of just plain text. Such TextBlock definition will look like this

<TextBlock Style="{StaticResource TextBlockStyle}" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Right">

<TextBlock.Text>

<Canvas>..Drawing here...</Canvas>

</TextBlock.Text>

</TextBlock>
Property Element syntax pertains the way have defined the TextBlock's property comprehensively (a detailed drawing object) instead of just a word "Title:". So this ability of XAML to support myriad of property definitions is branded by the magic word "Property Element Syntax". Just for the sake of readability we'll cover the next 2 concepts in the subsequent post which can be found here