Wednesday, September 26, 2012

My Silverlight 4 application get black in firefox means UI is not displaying, and the same crash in google chrome.

My Silverlight 4 application get black in firefox means UI is not displaying, and the same crash in google chrome.

My Silverlight 4 application get black in firefox means UI is not displaying, and the same crash in google chrome. 

Answers & Comments...

Answer: 1

Hi, please examine and compile your project to determine if it has any error. And make sure the object tag point to an correct xap file.

To help you further, we need more information about your issue, like exception message. Or you can upload your application(remove unrelated and sensitive code first) that can reproduce your issue to SkyDrive and show us the download link here.

Best Regards,





How Command handler can know which event has been raised ?

How Command handler can know which event has been raised ?

Hi,

for me this Command is bit confusing .I am implementing MVVM pattern in my project and often i need to use Command for exucuting methods in ViewModel . But sometimes i too need to know which actual event was raised in the View ?

e.g., there is a CheckBox control in View and Command property has been binded to a RelayCommand object in the ViewModel . Now , when the method is handled in ViewModel i need to know whether CheckBox's Checked event or UnChecked event was fired in the UI ?

Please if anybody can let me help clear my doubt . What is this Command actually used for ? There are already events like Checked , UnChecked , GotFocus , LostFocus , Click etc.... then why there was need for Command property ? Even if they have created what is speciality about that ! they are handled againt another event only .Like if CheckBox's Checked or UnChecked or Button's Click event is raised on UI then only Command property's underlying RelayCommand method is executed .

Anyway , going inside the RelayCommand's method is there any way to know which event was raised in the Client UI ?

Answers & Comments...

Answer: 1

Hi,

Take a look at Command section. In Silverlight you'd better use DelegateCommand of Prism, It is more function than RelayCommand.

http://msdn.microsoft.com/en-us/library/gg405484(v=pandp.40).aspx

 



Answer: 2

Yes, i have already read that quite long ago . Now what i need is , want to know which UI event was actually raised so that the Command object's method got executed .

<CheckBox Command="{Binding HandleThis}" />

Now ,lets see about this Checkbox . When HandleThis's underlaying method will execute ? Yea , you and no body is sure , it me be handled after CheckBox's Checked event , or it may be at CheckBox's UnChecked event ... or it may be bla..bla..etc...

So, is it possible to know which event was raised on UI , that triggered Command's underlaying method to exccute ?

Or my problem is not going to be clear ?



Answer: 3

jackWyu

jackWyu

There's no event was riased on UI except you use Trigger of Expression blend attach to Event.

Take a look at RelayCommand

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

Event and ICommand are diffrent.

 



Answer: 4

thaicarrot

jackWyu

jackWyu

There's no event was riased on UI except you use Trigger of Expression blend attach to Event.

Take a look at RelayCommand

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

Event and ICommand are diffrent.

 

That link i have also already gone through. And out of that i am in confusion about these Event and Command .

You said Event and ICommand are different . Yes they are different . Theoratically they are different , ICommand is an interface , Event is something like mechanism to handover some message to some other object to work another task. Yes these are theoratically and practically too well understood . But i am great confusion about the fact that how on Clicking on a Button , Command's underlaying method is called in the ViewModel code file ?

Command = "{Binding PropertyName}" . This PropertyName's underlayign object (RelayCommand Object) contains method , that is invoked . That's fine .It is invoked . But on the surface first of all there must have been Click event raised ! Since we have clicked on the Button , it must have raised Click event . But u are saying that ds'nt raises any event ? How it that going ? Hae , its going to be a black magic for me. All the resources link that u provided i have already gone through , and i have come up with confusions out of those documents . They are mine gererated . Anybody can help me here to get out ?



Answer: 5

jackWyu

jackWyu

It is riased click event.

public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(              "Command",              typeof(ICommand),              typeof(ButtonBase),              new PropertyMetadata(OnSetCommandCallback));  
 
 



Answer: 6

thaicarrot

It is riased click event.

Yes, that i want to know in the method that is called in ViewModel . Is it possible ?

Which event was raised in the UI ? In case of button here it was click . Lets say there were a CheckBox , then it may be Click , Checked or UnChecked etc. that i want to know in the ViewModel's method , that which event was actually raised in the UI .



Answer: 7

jackWyu

jackWyu

It is depending on who implement those lagic, Inside the event they call the ICommand's ExecuteCommand(); then fire at viewmodel.



Answer: 8

If you do something like this:

      <CheckBox Command="{Binding MyCommand}" IsChecked="{Binding IsChecked, Mode=TwoWay}"/>    

Then when the Command MyCommand is executed, the viewmodel will ALREADY have the IsChecked property set.  Then in the command, you might want to take different actions based on the IsChecked property value of the viewmodel.

That would be a reason to have a Command on a checkbox.  But there is no reason to need to know the event that I can think of.

Did you have something specific in mind?

Another possiblity, if you have multiple bindings to the command and you want to know which one it was, you could just use a CommandParameter to identify the source of the command.



Answer: 9

mtiede@swtechnologies.com

Another possiblity

Yea, you are somewhat closer to me . Let me simplify that.

Take simple CheckBox ,

<CheckBox Command="{Binding MyCommand}" />  



When the Command MyCommand is executed ... please wait here .Just hold on.
Let me interrogate , when this MyCommand gets executed ? Please think here , don't be in hurry ,when ?

When you think you will realize where i was confused . It can be Checked or Unchecked any of the UI event . In both cases MyCommand gets executed .
This is my confusion . When i am in MyCommand , i want to know user raised which event on the screen ?
I don't think my question was that confusing , but i think you people did'nt read my problems carefully and unnecesseryly we wasted our time .
Anyway , can i hope now ?



Answer: 10

I'm not sure what you are asking.  As I said, if you do this:

<CheckBox Command="{Binding MyCommand}" IsChecked="{Binding IsChecked, Mode=TwoWay}"/>    

The IsChecked bound property will be set first.  So when the command is triggered, you can just look at your Viewmodel property to decide what the command should do based on the state of the property.

I see no reason to know which event is involved.  Probably ever.

Maybe your problem would be clearer if you posted an example.

On re-reading your original post, I see you are also asking why did they make Checked, Unchecked AND Command.  And the answer is historical.  At first there was NO Commanding, at all.  And with the advent of MVVM, commands were added.  But the old Checked and Unchecked, for instance, are still there for backward compatibility.

But I wouldn't recommend doing anything other than my example above which should cover everything you need.  Don't use the old style.



Answer: 11

Yea,

you reached there .

mtiede@swtechnologies.com

The IsChecked bound property will be set first.

This i was unknown . This was one of the loophole.

mtiede@swtechnologies.com

I see no reason to know which event is involved.  Probably ever.

Now , to me also there seems no reason to know which event is involved . But still for my knowledge i want to know is that possible ?

Though presently it is of no use , but if we need can we know that ?

mtiede@swtechnologies.com

And the answer is historical.  At first there was NO Commanding, at all.  And with the advent of MVVM, commands were added.

Can you suggest some text books for this , that covers Silverlight 5 with MVVM .



Answer: 12

I don't think there is any way to know  which event and the reason for that is that you should never need to know.

I don't know about books.  I learned everything from the videos that are in the Learn tab at the top of the page.  (Back then the videos were different ones and I think in some regards better than the current ones).  And by reading a WPF book "Pro WPF in C# 2008".

The SL home page used to have links to books.  Maybe it is still somewhere here on the site.





How to Multi-Binding in silverlight?The parameter may be control like button,gridview,sender,e

How to Multi-Binding in silverlight?The parameter may be control like button,gridview,sender,e

How to Multi-Binding  in silverlight?The parameter may be control like button,gridview,sender,e.

I have realize one binding,but multi-binding I don't know how to do ,the sample I find multi-binding all is about biding string text,but control!

How to multi-binding control(sender,e,button)?

Answers & Comments...

Answer: 1

http://www.scottlogic.co.uk/blog/colin/2010/08/silverlight-multibinding-updated-adding-support-for-elementname-and-twoway-binding/

http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.bindingvalidationerror(v=vs.95).aspx

http://stackoverflow.com/questions/8692073/confusion-on-silverlight-user-control-custom-property-binding



Answer: 2

Hi Scaukenny,

You can utilize the custom markup extensions introduced in Silverlight5 to write a MultiBinding implementation with similar syntax and functionality which has been elaborated in below blog:

http://www.codeproject.com/Articles/286171/MultiBinding-in-Silverlight-5

Hope it may help you.

Best Regards,





Delete selected objects from canvas

Delete selected objects from canvas

I m adding dynamically rectangle,ellipse etc inside the canvas........Clicking on Delete button, i want to delete the selected shape ........ Suggest some suitable solutions for deleting particular object from canvas

Answers & Comments...

Answer: 1
MyCanvas.Children.Remove(MyObject);  



Answer: 2

But i m able to know whether the selected object is rectangle,ellipse or any other shape???



Answer: 3

Jigna Punjabi

But i m able to know whether the selected object is rectangle,ellipse or any other shape???

What's the meaning? The seleted object is obvious i think.





Image Loading Problem

Image Loading Problem

I have created a simple child window as below

<controls:ChildWindow x:Class="LeanFleet.SL.ChildControls.ChildWindow1"             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"              xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"             Width="400" Height="300"              Title="ChildWindow1">      <Grid x:Name="LayoutRoot" Margin="2">          <Image Source="/Resources/refresh.png" Width="24" Height="24" />          <Button x:Name="CancelButton" Content="Cancel" Click="CancelButton_Click" Width="75" Height="23" HorizontalAlignment="Right" Margin="0,12,0,0" Grid.Row="1" />          <Button x:Name="OKButton" Content="OK" Click="OKButton_Click" Width="75" Height="23" HorizontalAlignment="Right" Margin="0,12,79,0" Grid.Row="1" />        </Grid>  </controls:ChildWindow>

 

When I open the chilld window, the image was displayed. Next I have created a class to create same child window as below

 

public partial class childwnd : ChildWindow      {          public childwnd()              : base()          {              Grid grd = new Grid() { Height = 200, Width = 200 };              Image img = new Image() { Source = new BitmapImage(new Uri("/Resources/refresh.png", UriKind.Relative)), Width = 24, Height = 24 };              grd.Children.Add(img);              this.Content = grd;          }        }

 

But , now if I open this, the image not displayed. Did I miss annything? 

 


 

Answers & Comments...

Answer: 1

I'm guessing the buttons are on top of the image in the first example and that would be undesirable.  Maybe you are wanting the image INSIDE one of the buttons?

Not sure why it wouldn't work in code.



Answer: 2

You can remove the buttons and the issue will be still there. This is a scale down test case of my orginal 2 problems which are

1. If I create a menuitem dynamically (from code behind) the menuitem icons are not displayed.

2. If I crate a combo box with images on a child window (from code behind), only the images loaded in the parent page are displayed in the combo and all others are blank.

After posting this issue here, I did some more investigations and found that, in the code behind if I specify

CreateOptions = BitmapCreateOptions.None

as Image property, the image is displayed. Though, I do not understand the logic but it solved the Issue#1

But the Issue#2 is still not resolved even if I add the above property.



Answer: 3

Where are the images you are trying to use?  Are they in the server folder?  Or in the client xap?  Or in a resource?  I'm assuming not in a resource since you are giving a path.  But if they are in a resource, how do the properties look?



Answer: 4

Images are kept in server in a folder (named 'Resources') under clientbin folder.



Answer: 5

Seems like it should work.  I wonder if the problem is that it is in a ChildWindow?  I've seen ChildWindow break stuff (like drag and drop, for instance).  Sorry, no other suggestions I can think of.



Answer: 6

I'm not sure ... but worth investigating I think

In the code version you are running on the client and so you will need to have a folder called Resources with refresh.png in it in your Silerlight project (eg not in the web hosting project).

The xaml version is referencing a folder withing the hosting project.



Answer: 7

I have solved the problem.

Two things discovered.

1. This problem happens from VS2010 server not from IIS

2. If I place the images directly in the clientbin folder (instead of any other folder in clientbin), everything works fine. I don't even need CreateOptions="none"

Thanks





Get dynamic value in the service method of WCF

Get dynamic value in the service method of WCF

Hi all,

I have a service which contain the method name as GetDetails.

In this method i am making a list of all information. Like -

while (dr.Read())
{
var ele = new DetailList
{
myID= data.getInt(dr, 0),
myName = data.getString(dr, 1),
Value = Math.Abs(data.getDecimal(dr, 2)),
Total = data.getInt(dr, 3),
Value1 = data.getDecimal(dr, 4)
};
DetailList.Add(ele);
}

The above is only 5 items added in the list like myID,myName...etc. 

Suppose i want add new value LastName in this list dynamically...then wht i want to do?

Answers & Comments...

Answer: 1

Hi Shrikant,

Shrikant Gawali

The above is only 5 items added in the list like myID,myName...etc. 

Suppose i want add new value LastName in this list dynamically...then wht i want to do?

Can you explain the question more clearly? What is the relationship between the new value and WCF method?

Best Regards,



Answer: 2

See,

I have a class that contain the 5 members id,fname,mname,lname and city with their get, set properties.

In my service there is a method name as getStudDetails which can return the list of all student details.

To get the details of the student i used a procedure. This procedure can return only the updated columns not all columns.

Every time this procedure can return different columns.

In the loop i am taking value by using the following code-

da = new SqlDataAdapter("MyQuery", con);
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
st = new studentCls()
{
vchid = ds.Tables[0].Rows[i].ItemArray[0].ToString(),
vchfname = ds.Tables[0].Rows[i].ItemArray[1].ToString(), 
vchmname=ds.Tables[0].Rows[i].ItemArray[2].ToString(),

vchlname=ds.Tables[0].Rows[i].ItemArray[3].ToString(),

vchcity=ds.Tables[0].Rows[i].ItemArray[4].ToString(),
};
std.Add(st);
}

Here when i execute the code this can not return anything.

I want the value of the member which can be selected by the query?

What is the exact solution ?



Answer: 3

Shrikant Gawali

This procedure can return only the updated columns not all columns.

Shrikant Gawali

Here when i execute the code this can not return anything.

Do you try to set a breakpoint to diagnose in which line it lost the datas? A blog for your reference:

#Stored Procedure in WCF Data Service

http://www.c-sharpcorner.com/uploadfile/dhananjaycoder/stored-procedure-in-wcf-data-service/

Best Regards,



Answer: 4

I am not getting the result because i am executing the procedure which can select only one,two,three..etc column at a time not the all column and in my loop there is 5 fields.

I want to implement the code as if procedure select 2 columns then also i want the result and if procedure select 5 columns then also it want to work...so wht is the solution?





Integrate C# asp.net with Silverlight 4

Integrate C# asp.net with Silverlight 4

Hi,

I am New to Silverlight Technology. I have one requirement which deals with rich internet UI and some drag-drop stuff.
My half of website pages are created in c# asp.net now my question is Can I integrate both? OR I will need to Create from scratch in Silverlight4
My Silverlight4 Application will need to use Session Variables,database values,Communicate with Javascript and many other things set by my previous pages,will be set by runtime modification by user So continuously push and pull operations from database will need to be happen.
on that basics can I interact with Silverlight4? or It will be feasible for me to Do all stuff from scratch in Silverlight4?

Thanking you in anticipation

Answers & Comments...

Answer: 1

http://www.codeproject.com/Articles/26379/Silverlight-integrated-into-ASP-NET-AJAX-Control-F

http://www.c-sharpcorner.com/uploadfile/raj1979/host-silverlight-in-Asp-Net/





Usercontrol with different values

Usercontrol with different values

I have a multi check box as a usercontrol

I have a search page and created a reference of the usercontrol

  <TextBlock Grid.Row="0" Grid.Column="1" Text="State" ></TextBlock>      <my:MultiCheck Grid.Row="1"  Grid.Column="1" x:Name="State"/>
Here in this usercontrol i need to load the States 
 
 <TextBlock Grid.Row="0" Grid.Column="1" Text="Country" ></TextBlock>   <my:MultiCheck Grid.Row="1"  Grid.Column="1" x:Name="Country"/>
Here in this usercontrol i need to load the Country 
 
i.e Usercontrols are loaded with different but we have the format alone as the usercontrol. I need to use 
InotifyProperty since i want to reload things on any changes in the selection

Answers & Comments...

Answer: 1

http://www.codeproject.com/Tips/452756/Add-checkbox-inside-Combobox-in-Silverlight

http://www.henrycordes.nl/post/2008/06/Create-a-UserControl-with-Silverlight-20-(Beta-x)---Part-2.aspx

http://stackoverflow.com/questions/1526767/silverlight-usercontrol-custom-property-binding





I NEED GetDaylightChanges

I NEED GetDaylightChanges

.Net has a TimeZone info for GetDaylightChanges.  I can't find it in Silverlight.  I hope it is somewhere that I can't find and NOT that someone decided not to publish the information that it obviously has.

I need to tell a server in a different timezone when the timezone where the Silverlight app is being run what datetimes are daylight savings time.  The SL app is just preparing information for a scheduler that runs on the server.  The server needs to know how to adjust scheduled times from multiple clients run in multiple timezones.

It isn't sufficient to know if the SL CURRENTLY is in DST which seems to be all that SL is willing to give up.

Please tell me there is an easy way to get this information in SL.

Answers & Comments...

Answer: 1

Hi, it seems that GetDaylightChanges is not supported in Silverlight so far, but I think you can build a WCF web service for you Silverlight to adjust scheduled times from multiple clients run in multiple timezones.

Here is a link that may help you: http://pholpar.wordpress.com/2011/01/29/how-to-get-the-assembly-version-number-from-the-build-date-and-vice-versa/ 



Answer: 2

Your link is missing and I don't see how a web service could help.  The server may be running on an entirely different time zone.  What I did was write a little wpf app that the user can use SL to download and that app puts all the information in the clipboard.  Then they can use SL's clipboard to read it in.

Multi-step solution and I don't like it, but it looks like it can't be done just in SL.

Would be really interesting to see that link.



Answer: 3

Have you tried bypassing the timezone+DST stuff and just use UTC?  Sounds  like it would be a lot simpler in this case.



Answer: 4

UTC is what was the source of problems in the first place.  I started off simply.  I had local times in my app.  I stored it on the server.  That worked fine on a local server.  Now the server is in a different time zone.  So when the client says start the app at 9am, the server won't see that time until 10am. 

So then I converted into and out of UTCs from the local client.  Now when the client says 9am, the server is told the UTC time.  So the server will schedule at a time that matches the clients 9am request.  And this works for all clients and all locations of servers.

There is at least one problem.  One of the schedule patterns is to schedule on a specific day/days.  So my customer said, schedule one at 9PM.  The UTC time was 1AM of the next day.  That part is fine.  The schedule is evaluated at the time the client wanted.  BUT the UTC time is a different DAY. 

So if the client wants it scheduled only on Sundays, at 9:01PM on Saturday, the UTC is 1:01AM Sunday.  So the TIME criteria to schedule is correct, but then when I ask the UTC what DAY it is, it says SUNDAY and off goes the job on the CLIENT'S Saturday when he wanted Sunday.

So now I am trying to get the local time information as in the UTC Offset, the Start and End datetime for Daylight Savings Time, and the Delta for the DST (which can be things like 1 hour, but can also be things like 1/2 hour).

So I will then convert the UTC back to the original requester's local time so that I can get the DAY in local time.

So, bottom line, I started out with local time only, switched to UTC on the server with translation in and out on the client, and that broke my scheduler, and I need the local time zone information.

Hence my need for GetDaylightChanges.

My solution is to provide a downloadable WPF app that gets the DST information and puts it in the clipboard.  Then the SL app can copy the clipboard and persist that info to the IsolatedStorage.  From then on, it can be stored with the schedule request so the corrections can be made.



Answer: 5

mmjj

Hi, it seems that GetDaylightChanges is not supported in Silverlight so far, but I think you can build a WCF web service for you Silverlight to adjust scheduled times from multiple clients run in multiple timezones.

Here is a link that may help you: http://pholpar.wordpress.com/2011/01/29/how-to-get-the-assembly-version-number-from-the-build-date-and-vice-versa/ 

That link would seem to have nothing to do with time.





silverlight and flash plugin are suddenly not working anymore in IE10 (desktop) [closed]

silverlight and flash plugin are suddenly not working anymore in IE10 (desktop) [closed]

silverlight and flash plugin are suddenly not working anymore in IE10 (desktop). I think the only new software installed these two days is Adobe Photoshop CS6, Is ps' problem? I tried every setting in IE10(Desktop not Metro), still not working. But in Chrome, everything works fine. Could anyone help me? Thanks.

No Answer and comments so far




How to Workaround Referencing View's Controls

How to Workaround Referencing View's Controls

I'm using Galasoft's Light MVVM for my Siverlight project.

I have setup everything as instructed: the ViewModel is bound to View's DataContext;

I have a canvas named inkCanvas in the View.

When the ViewModel gets the updated project data, I need to reference inkCanvas to create a CanvasRender instance public CanvasRender(Canvas canvas, ProjectData pdata).

The problem is in MVVM, the ViewModel knows nothing about View, so how can I reference a control (inkCanvas) in View?

P.S. (Edited): The workaround I made is: when I pass the project data to the ViewModel, I also pass the inkCanvas from View's code-behind. hmmm, now my code-behind is not clean.

Answers & Comments...

Answer: 1

In MVVM Pattern, you won't reference a Control directly in ViewModel. In MVVM, all is "binding". You inkCanvas will be binding to a property in your ViewModel.

public class MyViewModel : INotifyPropertyChanged {     private readonly StrokeCollection _mystrokes;      public MyViewModel ()     {         _mystrokes= new StrokeCollection();         (_mystrokesas INotifyCollectionChanged).CollectionChanged += delegate         {             //the strokes have changed         };     }      public event PropertyChangedEventHandler PropertyChanged;      public StrokeCollection MyStrokes     {         get         {             return _mystrokes;         }     }      private void OnPropertyChanged(string propertyName)     {         var handler = PropertyChanged;          if (handler != null)         {             handler(this, new PropertyChangedEventArgs(propertyName));         }     } } 

And XAML:

<InkCanvas Strokes="{Binding MyStrokes}"/> 

Edit :

Maybe the workaround for your case is to use EventToCommand : this allow tobind an UI event to an ICommand directly in XAML ( and use Args to pass a ref to the inkCancas)

<i:Interaction.Triggers>     <i:EventTrigger EventName="Loaded">         <cmd:EventToCommand Command="{Binding Mode=OneWay, Path=LoadedCommand}"                             PassEventArgsToCommand="True" />     </i:EventTrigger> </i:Interaction.Triggers> 
by : Cybermaxshttp://stackoverflow.com/users/1554201

Answer: 2

Per the comments above, one way to do this is to extend Canvas and keep the reference to CanvasRender inside that class.

public class MyCanvas : Canvas {     private CanvasRender _canvasRender;     private ProjectData _data;      public ProjectData Data     {         get { return _data; }                set         {             _data = value;             _canvasRender = new CanvasRender(this, _data);         }     }      public MyCanvas() : base()     {     } } 

You'd probably want to also make ProjectData a Dependency Property so that it's bindable.

This allows you to maintain the MVVM pattern, because now you can write in XAML:

<local:MyCanvas ProjectData="{Binding ViewModel.ProjectData}" /> 
by : dbasemanhttp://stackoverflow.com/users/1001985

Answer: 3

If your going to use the EventToCommand approach (which you tried in another answer), then instead of using the PassEventArgsToCommand property use the CommandParameter property and bind it to your Canvas.

<i:Interaction.Triggers>     <i:EventTrigger EventName="Loaded">         <cmd:EventToCommand Command="{Binding Path=CanvasLoadedCommand}"                             CommandParameter="{Binding ElementName=inkCanvas}" />     </i:EventTrigger> </i:Interaction.Triggers> 

Then in your ViewModel:

public class ViewModel {     private Canvas m_canvas;      public RelayCommand<Canvas> CanvasLoadedCommand { get; private set; }      public ViewModel()      {          CanvasLoadedCommand = new RelayCommand<Canvas>(canvas =>           {              m_canvas = canvas;         });      } } 

So as soon as your canvas is loaded, you should then have a reference to it saved in your view model.

by : bugged87http://stackoverflow.com/users/1575237




Silverlight app reload hangs at 100%

Silverlight app reload hangs at 100%

Why my silverlight page when I reload (F5) it hang is 100% and not into my apps (I tested, it not error). Please help me!

Answers & Comments...




inner height of browser at client side in silverlight

inner height of browser at client side in silverlight

I have silver light application.i want inner height of browser, i got it while running in localHost but when i am deploying it then it would give me error like.

object references not set to an instances of object

I have used following code to get the inner height of browser.

following code resides at client side.i have set the resolution at server side.

HtmlPage.Window.GetProperty("innerHeight"); 

Answers & Comments...

Answer: 1

I suppose that Application.Current.MainWindow should help you in Out-of-Browser Application.

And good article about Out-of-Browser Application may be useful for you.

by : AlexThttp://stackoverflow.com/users/1032426




Enabling In-browser elevated trust

Enabling In-browser elevated trust

I'm trying to get in-browser elevated trust to work and having an issue. I've:

  1. Purchased a certificate
  2. Signed the xap with that certificate
  3. Added AllowElevatedTrustAppsInBrowser=1 in the registry

Yet the app still doesn't think it is running in elevated trust. Any ideas on what I might be missing?

Running off localhost, of course, works because it doesn't require any of the above.

Screenshots included below as proof.

enter image description here Certificate Store

Answers & Comments...

Answer: 1

So you have your certificate from a trusted publisher. You have signed the XAP. You have installed the certificate on the client computers.

Have you configured the registry on the client as described in this post?

You can also configure the registry settings using Group Policy

by : TriggerPinhttp://stackoverflow.com/users/1549726

Answer: 2

I also had same problem!

I'm configured the registry on the client computer and import certificate to Trust Root and Trust Publishes on client computer!

The different is I use test certificate file create by Visual Studio

What shall I do?

by : Dionixhttp://stackoverflow.com/users/1338069




Silverlight WCF Service Client Instantiation

Silverlight WCF Service Client Instantiation

I'm encountering a problem when creating the WCF service client object.

HelloServiceClient helloWorldClient = new HelloServiceClient("BasicHttpBinding_IDataAccess");

Here's the content of my ServiceReferences.ClientConfig

<configuration>   <system.serviceModel>     <bindings>       <basicHttpBinding>         <binding name="BasicHttpBinding_IDataAccess" maxBufferSize="2147483647"             maxReceivedMessageSize="2147483647">           <security mode="None" />         </binding>       </basicHttpBinding>     </bindings>     <client>       <endpoint address="http://localhost:8732/Design_Time_Addresses/HelloWcf/Service1/mex" binding="basicHttpBinding"           bindingConfiguration="BasicHttpBinding_IDataAccess" contract="IHelloService"           name="BasicHttpBinding_IDataAccess" />     </client>   </system.serviceModel> </configuration> 

The error message is as following

System.InvalidOperationException: Could not find endpoint element with name 'BasicHttpBinding_IDataAccess' and contract 'ServiceReference1.IHelloService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this name could be found in the client element. at System.ServiceModel.Description.ConfigLoader.LoadChannelBehaviors(ServiceEndpoint serviceEndpoint, String configurationName) at System.ServiceModel.ChannelFactory.ApplyConfiguration(String configurationName) at System.ServiceModel.ChannelFactory.InitializeEndpoint(String configurationName, EndpointAddress address) at System.ServiceModel.ChannelFactory1..ctor(String endpointConfigurationName, EndpointAddress remoteAddress) at System.ServiceModel.EndpointTrait1.CreateSimplexFactory() at System.ServiceModel.EndpointTrait1.CreateChannelFactory() at System.ServiceModel.ClientBase1.CreateChannelFactoryRef(EndpointTrait1 endpointTrait) at System.ServiceModel.ClientBase1.InitializeChannelFactoryRef() at System.ServiceModel.ClientBase`1..ctor(String endpointConfigurationName) at SilverlightApplication1.ServiceReference1.HelloServiceClient..ctor(String endpointConfigurationName) at SilverlightApplication1.MainPage.Button_Click(Object sender, RoutedEventArgs e)

Could someone help me on this problem? and please do let me know if you want any other codes/config.

Answers & Comments...

Answer: 1

As found above - the contract name needs to be 'ServiceReference1.IHelloService' as indicated in the error.

by : BugFinderhttp://stackoverflow.com/users/687262




Why does binding take so long in WP7? I can see it happening

Why does binding take so long in WP7? I can see it happening

I am populating a list searchResults in the Loaded event of a page.

If this loading takes 50ms, then when I load the page by navigating back to it, I will see the previous searchResults for a fraction of second before the binding completes.

a) In what event can I bind controls before the page becomes visible? (The page is being navigated back to, so the constructor is not called again.)

b) Is there any way to force a binding to happen in the Loaded event code? I notice that list1.ItemSource=x bindings seem to be done after the event function falls out of scope. As if they are done in OnIdle.

More details on b)

If I run the following code:

(ItemsControl) lstSearchResults.ItemSource = searchResults; int iCount = lstSearchResults.Items.Count 

iCount will be zero whether there are items in the searchResults or not.

Is there a way to bind lstSearchResults to searchResults that populates straight away?

Answers & Comments...

Answer: 1
  1. OnNavigatedTo event is being called, you can try doing your work there
  2. I am not completely sure what you mean but if you already did the binding between an observable collection and a listbox, then the changes you make to the observable collection will reflect in the listbox.
by : igralihttp://stackoverflow.com/users/793467

Answer: 2

1) Associate your DataContext to your viewModel and Bind the list on the UI itself using ItemsSource={Binding searchResults}"

2) On the Loaded event do lstSearchResults.ItemSource = searchResults;

Note that it is recommended that if your list is dynamic to have the lis as ObservableCollection

If searchResults are variable height items it may take time for the UI binding depending upon the ItemTemplate. To tackle that problem one should use Virtualizing StackPanel which is already a part of ListBox Control. Hence it is highly unlikely the problem to arise in your case if you are already using a listbox. For further detailed information you may go through this resource. I hope it helps.

by : Milan Aggarwalhttp://stackoverflow.com/users/1378956




Validate Coordinate entry using RegEx

Validate Coordinate entry using RegEx

I was wondering if anybody could help with some RegEx validating. I have a text box where a user is to input a set of XY coordinates e.g. 123.345, 543.123 I can use the following bit of RegEx to check for a single X or Y coordinate. var pattern = "^[0-9]+[.]?[0-9]*$"; Allows only numbers and 1 decimal point to be entered.

But I can't figure out how to allow the user to enter a single whitespace and/or a comma after the X coordinate and then continue to enter the Y coordinate.

I know this would be easier with two different textboxes but because of the application and UI requirements I cannot add a second text box for the Y coordinate.

Thanks for any help!

Answers & Comments...

Answer: 1

Try this :

^\d+(?:.\d+)?,\s\d+(?:.\d+)$

Explanation :

(1)    ^                 => Beginning of input (2)    \d+(?:\.\d+)?     => Allow one or more digits followed optionally by a dot and one or more digits (3)    ,\s               => Expect a comma and a single whitespace (4)    \d+(?:\.\d+)      => See (1) (5)    $                 => End of input 

Nota : If you expect only a single space change ,\s into ,[ ].

by : Stephanhttp://stackoverflow.com/users/363573




What is Smooth Streaming Media Element TotalBytesDownloaded

What is Smooth Streaming Media Element TotalBytesDownloaded

I want to know what is TotalBytesDownloaded field, in Microsoft.Web.Media.SmoothStreaming. MSDN conveniently states it as "The number of bytes downloaded.". But is it the number of video-bytes downloaded by the player or all the bytes including any other server requests and response you might be making on top of the player(for logging purposes)

Answers & Comments...

Answer: 1

It's the total number of bytes downloaded for both video and audio requests for an AV presentation.

by : Vishal Soodhttp://stackoverflow.com/users/1538843




How to check get list code in LightSwitch 2011?

How to check get list code in LightSwitch 2011?

LightSwitch automatically generates most of the code. I was wondering anyone knows how to check the get list code in LightSwitch 2011 ? Where is it located ?

Root Issue: The reason I'm looking for it is to address the below issue. I still can't quite understand whether it is a bug in LightSwitch or something wrong with my data model or code.

Comparing two fields using LINQ

Drop Down Problem in LightSwitch

Answers & Comments...




WebClient and caching in Silverlight + WP7

WebClient and caching in Silverlight + WP7

I am using WebClient to download a JSON file everytime my WP7 application loads. I am loading all the details in one shot and that too from a server endpoint serving this JSON. The obvious problem I faced was the caching. It was always loading the stale copy. But I tackled this issue by adding a dummy URL paramater at the end.

However, the JSON changes very rarely. So I still need to utilize the caching technique that the WebClient automatically uses. To do this I initially request a call to the server's JSON version something like, http://myserver/JSONVersion. This JSONVersion gets updated any time JSON is updated.

Once I get it, i append it to my url http://myserver/myjson.json?v=(JSONVERSION). This has solved my entire problem. However, I feel this is very ugly and has unnecessary excess code+logic floating around. I am hoping the HTTP Cache headers have a work around similar to the one that I am having. If so, please let me know.

Answers & Comments...




How to set http header If-Modified-Since on a WebRequest in Windows Phone 7?

How to set http header If-Modified-Since on a WebRequest in Windows Phone 7?

Trying to set the 'If-Modified-Since' header in wp7:

request.Headers[HttpRequestHeader.IfModifiedSince] = dateString; 

Gives the error:

This header must be modified with the appropriate property.

Which means that the property .IsModifiedSince should be used on the request class, as described in MSDN: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.ifmodifiedsince.aspx

But this property does not exist in Silverlight i.e. WP7.

Has anyone been able to set this header for a http request on Windows Phone 7?

Shawn Wildermuth posted this problem back in September 2010, with no solution: http://social.msdn.microsoft.com/Forums/en/windowsphone7series/thread/8aec7481-2cf3-4047-b0d4-05d4313a9e4c

Thank you!

Answers & Comments...

Answer: 1
request.Headers.Add("If-Modified-Since", datestring); 
by : Chris Kookenhttp://stackoverflow.com/users/171742

Answer: 2

You can just use the string that HttpRequestHeader.IfModifiedSince represents:

request.Headers["If-Modified-Since"] = dateString;  

I've had to do this with a number of other headers which WP7 doesn't expose helper methods for setting.

Update
Based on the remarks at http://msdn.microsoft.com/en-us/library/8y7x3zz2(v=VS.95).aspx it would appear that it is not possible to set this header in WP7.

As an alternative you could create your own proxy server to handle the caching for your app.

by : Matt Laceyhttp://stackoverflow.com/users/1755

Answer: 3

The short answer is: It cannot be done, not supported.

Solution would be, as Matt Lacey states, to create a proxy class to handle this.

That proxy would set

request.AllowStreamReadBuffering = false; 

and then parse the response until the header ends or the header value has been found.

Note! This workaround limits the data downloaded to the phone, but not the work needed by the server to process the request.

by : andyhammarhttp://stackoverflow.com/users/107902

Answer: 4

This can only be set on the HTTPWebRequest object so casting the WebRequest should allow you to set the property eg:

((HttpWebRequest)request).IfModifiedSince = modifiedDate; 

It takes a DateTime object so you may need to parse the string first.

by : I draw a line when I'm Deadhttp://stackoverflow.com/users/1699810




The latest trends in designing windows based desktop application [closed]

The latest trends in designing windows based desktop application [closed]

I have an application written in C#, using .Net 4.0 framework. As the application is kind of an old application, so its using window forms. The application is very simple for now, it doesn't have high graphical interface like using WPF and Silverlight. I have now decided to move the application to the next level, the latest, one using current trends and great user interface. What are my options of improving this application design wise, performance wise and looks wise? Like using WPF, MS Silverlight or any other cool technology out there?

I kinda more need ideas what can I do to get to high tech application? Some examples of some cool applications would be also appreciated.

A little about the application:

Its a windows desktop application, using Access as a database used for some finance analysis.

If more information needed? Please let me know.

No Answer and comments so far




sharepoint silverlight web part does not work on server

sharepoint silverlight web part does not work on server

I've developed a Lync Silverlight application and it is working on my local machine. Then I needed to add this Silverlight to a Sharepoint site, thus i used Silverlight web part. It is OK on my local Sharepoint site but when i install it to server i could not see the Silverlight and not getting error.

I am using web service on my Silverlight application. I check that server can access to web services. My development environment is Visual Studio 2010 and Lync Server 2010. Also I am using Sharepoint 2010.

Here is what i tried for the solution:

  1. Check the whether IIS is configured for xap - OK
  2. I tried to install xap file through Sharepoint module, it did not work.
  3. I tried to use a visual web part, it did not work.
  4. I tried to embed xap file to an HTML page for debugging, there was no error.

Now i am stuck. Any suggestion will be appreciated.

Answers & Comments...

Answer: 1

Have you cross-verify with which Silverlight sdk version you have developed your silverlight application.

And server is having that version installed?

if it's working fine with your local server then it also works fine with another server.

regards.

by : Suresh Lakumhttp://stackoverflow.com/users/1699270




"SingleInstanceHost" flag for Silverlight App

"SingleInstanceHost" flag for Silverlight App

I found out some interesting flag named "SingleInstanceHost" for silverlight app, which can be set in Application Manifest File. Msdn says that it "Indicates whether the application has a single instance host".

Can anyone explain what does this flag mean?

My test: 1. If I run my wp7 silverlight app on device WITHOUT this flag, then if I try to run the second app instance from start menu - the system kills the 1st instance and runs the new one.

  1. If I run my wp7 silverlight app on device WITH this flag, then if I try to run the second app instance from start menu - the system kills the 1st instance and DOES NOT run the new one.

Strange behavior!

Answers & Comments...




MVVM way to wire up event handlers in Silverlight

MVVM way to wire up event handlers in Silverlight

Using an MVVM pattern in Silverlight/WPF, how do you wire up event handers? I'm trying to bind the XAML Click property to a delegate in the view model, but can't get it to work.

In other words, I want to replace this:

<Button Content="Test Click" Click="Button_Click" /> 

where Button_Click is:

private void Button_Click(object sender, RoutedEventArgs e)  {      // ... } 

with this:

<Button Content="Test Click" Click="{Binding ViewModel.HandleClick}" /> 

where HandleClick is the handler. Attempting this throws a runtime exception:

Object of type 'System.Windows.Data.Binding' cannot be converted to type 'System.Windows.RoutedEventHandler'.

Answers & Comments...

Answer: 1

The answer is to use the extensions provided by Microsoft in the Prism framework. With the DLLs System.Windows.Interactivity.dll and Microsoft.Expression.Interactions.dll, it's possible to bind an event to a handler method in a view model:

<Button Content="Test Click"     xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"           xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"     >     <i:Interaction.Triggers>         <i:EventTrigger EventName="Click">             <ei:CallMethodAction TargetObject="{Binding ViewModel}" MethodName="HandleClick" />         </i:EventTrigger>     </i:Interaction.Triggers> </Button> 
by : dbasemanhttp://stackoverflow.com/users/1001985

Answer: 2

The MVVM way to do so is by using commands and the ICommand interface. The Button control has a property named Command which receives an object of type ICommand

A commonly used implementation of ICommand is Prism's DelegateCommand. To use it, you can do this in your view model:

public class ViewModel {     public ICommand DoSomethingCommand { get; private set; }      public ViewModel()     {         DoSomethingCommand = new DelegateCommand(HandleDoSomethingCommand);     }      private void HandleDoSomethingCommand()     {         // Do stuff     } } 

Then in XAML:

<Button Content="Test Click" Command={Binding DoSomethingCommand} /> 

Also, make sure that the viewmodel is set as your view's DataContext. One way to do so is in your view's code-behind:

this.DataContext = new ViewModel(); 

This article is a good place to start if you want to know more about MVVM.

by : Adi Lesterhttp://stackoverflow.com/users/389966




Application Bar as in media player which will be horizontal or landscape

Application Bar as in media player which will be horizontal or landscape

I have seen how to create application bar in wp7 but it changes according to its orientation but i have a landscape page which will show animation. I need to force application bar to be bottom of the page not vertical. Its like video player the controls play,pause and stop will be at the bottom so is there any example or procedure to do it please need answers

Thank You

Answers & Comments...




Data Contract does not appear in Service reference... How can I add it?

Data Contract does not appear in Service reference... How can I add it?

I have a silverlight application that runs WCF services.

I have created a WCF service on the server side, it has a data contract. I have also added the service reference on the client side.

I now want the client side to be able to access the data from the server side, so when i tried writting serviceReference.dataContract_Name, it didnt work.

The data contract does not appear in the service reference either.

I dont know if this makes sense, can someone identify what it is?

Thanks.

Answers & Comments...

Answer: 1

If you wanna get data contract on client side, you should declare operation contract with this data contract as argument or as return type. Check this in your code, it can be the reason.

by : Vladimir Dorokhovhttp://stackoverflow.com/users/493995




Silverlight 4 custom control (Button, TextBox and ComboBox)

Silverlight 4 custom control (Button, TextBox and ComboBox)

In my custom control, I have one Button, TextBox and ComboBox and loaded the custom control at run time successfully. When I am selecting the item from the combo box – position of the drop down menu move left side. I want open drop down menu exactly under the combo box.

Please Help....

Below code is my custom control - Generic.xaml file:

<Style TargetType="control:TextBox">     <Setter Property="Template">         <Setter.Value>             <ControlTemplate TargetType="control:TextBox">                 <StackPanel Orientation="Horizontal">                     <Button Name="GotoIcon" Cursor="Hand" VerticalContentAlignment="Top" IsTabStop="False" />                     <StackPanel Orientation="Horizontal">                         <Border x:Name="Border" Opacity="1" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="1" Width="{TemplateBinding TextBoxWidth}">                             <ScrollViewer x:Name="ContentElement" BorderThickness="0" IsTabStop="False" Padding="{TemplateBinding Padding}"/>                         </Border>                         <ComboBox x:Name="ComboElement" IsTabStop="True" BorderThickness="0" Padding="{TemplateBinding Padding}" Visibility="Collapsed" Width="{TemplateBinding TextBoxWidth}"/>                     </StackPanel>                 </StackPanel>             </ControlTemplate>         </Setter.Value>     </Setter> </Style> 

Answers & Comments...




"ConfigFileMissing" error when silverlight client register for duplex channel on self hosted WCF service

"ConfigFileMissing" error when silverlight client register for duplex channel on self hosted WCF service

I am getting CofigFileMissing error when my silverlight client requests a duplex channel on a self hosted WCF service. Silverlight client has clientaccesspolicy.xml at its root, and client endpoint is mentioned in its web.config. The WCF service get started properly and its configuration is in app.config present at the statup project.

Any help would be highly appreciated. Since I am stuck because of this error.

Following is the stacktrace for the error-

[XmlException: [Xml_InternalError] Arguments: Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version=5.0.61118.00&File=System.Xml.dll&Key=Xml_InternalError] System.Xml.XmlXapResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn) +329 System.Xml.XmlReaderSettings.CreateReader(String inputUri, XmlParserContext inputContext) +109 System.Xml.XmlReader.Create(String inputUri, XmlReaderSettings settings, XmlParserContext inputContext) +44 System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup() +78

[InvalidOperationException: [ConfigFileMissing] Arguments: Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version=5.0.61118.00&File=System.ServiceModel.dll&Key=ConfigFileMissing] System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup() +136 System.ServiceModel.Configuration.ServiceModelSectionGroup.get_Current() +19 System.ServiceModel.Description.ConfigLoader.LookupChannel(String configurationName, String contractName, Boolean wildcard) +35 System.ServiceModel.Description.ConfigLoader.LoadChannelBehaviors(ServiceEndpoint serviceEndpoint, String configurationName) +56 System.ServiceModel.ChannelFactory.ApplyConfiguration(String configurationName) +44 System.ServiceModel.ChannelFactory.InitializeEndpoint(String configurationName, EndpointAddress address) +66 System.ServiceModel.DuplexChannelFactory1..ctor(Object callbackObject, String endpointConfigurationName, EndpointAddress remoteAddress) +103 System.ServiceModel.InstanceContext.System.ServiceModel.IInstanceContext2.CreateChannelFactory(String endpointConfigurationName) +61 System.ServiceModel.EndpointTrait1.CreateDuplexFactory() +150 System.ServiceModel.ClientBase1.CreateChannelFactoryRef(EndpointTrait1 endpointTrait) +22 System.ServiceModel.ClientBase1.InitializeChannelFactoryRef() +46 System.ServiceModel.ClientBase1..ctor(IInstanceContext callbackInstance) +111 System.ServiceModel.DuplexClientBase`1..ctor(InstanceContext callbackInstance) +5 UINx.Framework.Client.ServiceModule.SL.PivotViewerClient..ctor(InstanceContext callbackInstance) +37 UINx.Framework.Client.ServiceModule.SL.PivotViewerService.RequestResources(BaseRequest request) +100 UINx.IA.Client.ResourceManagement.Workflow.SL.BOPivotViewer.GetResources(String filterId) +156 UINx.IA.Client.ResourceManagement.UILayer.ViewModel.SL.PivotViewerViewModel..ctor(String FILTERID, BOPivotViewer boPivotViewer) +158 PivotDataViewer.Web.PivotDataViewerRequestPage.Page_Load(Object sender, EventArgs e) in d:\Code_Dev\IAResourceManagement05Sep2012\ResourceManagement\PivotDataViewer.Web\PivotDataViewerRequestPage.aspx.cs:25 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51 System.Web.UI.Control.OnLoad(EventArgs e) +92 System.Web.UI.Control.LoadRecursive() +54 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772

Answers & Comments...




Silverlight Set Custom Tool Tip Programmatically

Silverlight Set Custom Tool Tip Programmatically

I have created the following custom tooltip with the custom template.

<ToolTip x:Class="FireFly.Controls.CustomToolTip" 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" d:DesignHeight="300" d:DesignWidth="400"> <ToolTip.Style>     <Style TargetType="ToolTip">         <Setter Property="Template">             <Setter.Value>                 <ControlTemplate TargetType="ToolTip">                     <Border>                         <Border.Background>                             <RadialGradientBrush>                                 <GradientStop Color="WhiteSmoke"/>                                 <GradientStop Color="#FFE0E0E0" Offset="1"/>                             </RadialGradientBrush>                         </Border.Background>                         <ContentPresenter Content="{TemplateBinding Content}"                                 ContentTemplate="{TemplateBinding ContentTemplate}"                                 Margin="{TemplateBinding Padding}"                                  VerticalAlignment="Center"/>                     </Border>                 </ControlTemplate>             </Setter.Value>         </Setter>     </Style> </ToolTip.Style>     

What i need to do is, from within a behvior i need to set the tooltip of the assosciated object to an instance of my custom tool tip control.

Something like

toolTip = new CustomToolTip() {Content = new TextBlock() {Text = text, FontSize = 12}}; 

However this isn't working.

Could someone possibly point me in the right direction?

Thanks

Steve

Answers & Comments...




Scrape data with Python from Silverlight application?

Scrape data with Python from Silverlight application?

I'm curious is there a way from Python/IronPython to communicate with remote Silverlight application.What I'm looking for is a way to log into remote silverlight app and parse data, the way that Curl enables to log into remote website with Post request and get html.I know that Silverlight is not a simple web page and its not probably easy, but there's not many information on this particular problem.I read that IronPython have Silverlight support, but I don't know right now much about .net and wondering if I have hit a dead end.Thanks.

Answers & Comments...




How do I access the UI elements within an ItemsControl?

How do I access the UI elements within an ItemsControl?

I have subclassed a Silverlight ItemsControl into a SlideShow control. This works fine when I hard-code the item elements in the XAML directly. But if I use a DataTemplate, how do I access the UI elements for each item?

Answers & Comments...

Answer: 1

Parse through it with a foreach statement?

eg:

foreach (ChildObject c in ParentObject.Children)

by : Peterhttp://stackoverflow.com/users/1658168

Answer: 2

The ItemsControl may create new items for them as items come and go, so you have to use ItemsControl.Items to get each data item, then use ItemsControl.ItemContainerGenerator.ContainerFromItem (or other methods on the ItemContainerGenerator to find the UI element for that item that was created by the DataTemplate

see: http://msdn.microsoft.com/en-us/library/system.windows.controls.itemcontainergenerator(v=vs.95).aspx

by : John Gardnerhttp://stackoverflow.com/users/13687




Binding to Listbox programattically in silverlight

Binding to Listbox programattically in silverlight

I want a listbox that will show all the images and text "layers" that I have on my Canvas in silverlight. The code I have currently crashes when I try to view the listbox or when I'm viewing the listbox when I add an element. I can't figure out why. Can someone point me in the right direction with this?

XML -

                            <Grid DataContext="{Binding Path=Project}">                                 ...                                 ...                                 <TextBlock Name="textBlock1" Text="Layers" Margin="18,16,0,0" />                                  <StackPanel Grid.Row="1" Grid.RowSpan="2" Grid.ColumnSpan="2">                                     <ListBox ItemsSource="{Binding Path=Elements}" Height="175" Name="listBox1" Width="172"/>                                 </StackPanel>                              </Grid> 

Project.cs

        //List of elements     private ObservableCollection<FrameworkElement> elements;     public ObservableCollection<FrameworkElement> Elements     {         get { return elements; }         set         {             elements = value;             NotifyPropertyChanged("Elements");         }     } // An example of how an element is added to the Elements collection // There are also image elements added similarly private void AddTextElement(object param)     {         TextBlock textBlock = new TextBlock();         textBlock.Text = "New Text";         textBlock.Foreground = new SolidColorBrush(Colors.Gray);         textBlock.FontSize = 25;         textBlock.FontFamily = new FontFamily("Arial");         textBlock.Cursor = Cursors.Hand;         textBlock.Tag = null;           this.Elements.Add(textBlock);         numberOfElements++;           this.SelectedElement = textBlock;         this.selectedTextElement = textBlock;     } 

Answers & Comments...

Answer: 1

One reason might be, because you bind using Path property in your Grid element.

You should use binding source, and set your Project object as a staticresource which you can point to when you call binding source.

Like this:

<Window     xlmns:local="NamespaceOfMyProject">      <Window.Resources>         <local:Project x:key="MyProjectResource" />     </Window.Resources>      <Grid DataContext="{Binding Source={StaticResource MyProjectResource}}>     ....     </Grid>     .... </Window> 

Reason is: You use "Source" when you point to objects, and "Path" when you point to properties.

Another way to set the DataContext is to do it in the codebehind, using this C# code. But first give your grid a name, so it can be referenced in the codebehind:

<Grid x:Name="myGrid"> 

Codebehind:

myGrid.DataContext = new Project(); 
by : Johnnyhttp://stackoverflow.com/users/1640121




Silverlight projects stopped compiling under "Any CPU" option

Silverlight projects stopped compiling under "Any CPU" option

I have an x64 build server that has been compiling Silverlight projects for a long time without any issues. Then suddenly it started complaining "Silverlight 4 SDK is not installed" and now I can compile SL projects only under "x86" platform. I'd like to continue using "Any CPU" for all projects but I can't figure out what happened.

Answers & Comments...

Answer: 1

This issue is nearly always due to an incorrect invocation of the x64 version of MSBuild. Ensure that you are using the x86 version of the build tools.

by : Nick Nieslanikhttp://stackoverflow.com/users/750796




Simple RichTextBox/XAML conversion

Simple RichTextBox/XAML conversion

I'm trying to remember where I saw a small Silverlight demo of a RichTextBox editor that let you enter/format text, and then on another view see the XAML version of the same text.

I'm trying to format a very simple Word document (paragraphs, bold, bullets, etc) into something I can put into a RichTextBlock on WinRT, but can't seem to find anything that does a decent and clean conversion.

I tried the project at http://wordtoxaml.codeplex.com/, but it didn't support bullets and the output was extremely messy.

Answers & Comments...




Error Loading Component

Error Loading Component

I'm converting a Silverlight 3 project to Silverlight 4. I recently got the project able to run, but I am running into problems instantiating a search window. VS threw the following error at me:

Microsoft JScript runtime error: Unhandled Error in Silverlight Application Set property 'System.Windows.FrameworkElement.Style' threw an exception. [Line: 242 Position: 46]   at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)    at ESM.Visualization.SearchWindow.InitializeComponent()    at ESM.Visualization.SearchWindow..ctor(Map mapWindow, String addressServiceUrl, String projectServiceUrl)    at ESM.Visualization.MainPage.InstantiateSearchWindow()    at ESM.Visualization.MainPage.MapWindow_Progress(Object sender, ProgressEventArgs e)    at ESRI.ArcGIS.Client.Map.layersProgressHandler(Object sender, ProgressEventArgs args)    at ESRI.ArcGIS.Client.LayerCollection.layer_OnProgress(Object sender, ProgressEventArgs args)    at ESRI.ArcGIS.Client.Layer.ProgressHandler.Invoke(Object sender, ProgressEventArgs args)    at ESRI.ArcGIS.Client.Layer.OnProgress(Int32 progress)    at ESRI.ArcGIS.Client.DynamicLayer.bitmap_DownloadProgress(Object sender, DownloadProgressEventArgs e, Image img, EventHandler`1 onProgressEventHandler, Int32 id)    at ESRI.ArcGIS.Client.DynamicLayer.<>c__DisplayClass7.<getSourceComplete>b__4(Object sender, DownloadProgressEventArgs e)    at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)    at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName) 

I researched the error and tried re-installing Silverlight in accordance to this solution. But the error still occurred. I looked at this SO question, but my App.xaml is hardly 242 lines. Here's my MainPage.xaml at around line 242:

<StackPanel Orientation="Vertical" HorizontalAlignment="Left" Grid.Row="2" VerticalAlignment="Bottom">             <esriToolkit:Navigation x:Name="MapNavigation" Margin="5" Map="{Binding ElementName=MapWindow}" Visibility="Collapsed"  />             <!--<esri:ScaleBar x:Name="MainScaleBar" Margin="5" MapUnit="DecimalDegrees" Foreground="Black"                  Map="{Binding ElementName=MapWindow}"                 DisplayUnit="Miles" Visibility="Visible" />--> </StackPanel> 

And here is the .xaml for the search window I am trying to instantiate (at around line 242):

<grid:AgDataGrid x:Name="grdAddressResults" Grid.Row="1" Grid.Column="0" ColumnsAutoWidth="True"                                  ShowTotals="False" FocusMode="Row" FocusedRowChanged="grdResults_FocusedRowChanged"                                  IsMultiSelect="False" Margin="0,10,0,0">                                 <grid:AgDataGrid.Columns>                                     <grid:AgDataGridColumn FieldName="Address" />                                     <grid:AgDataGridColumn FieldName="X" Visible="False" />                                     <grid:AgDataGridColumn FieldName="Y" Visible="False" />                                 </grid:AgDataGrid.Columns>                                 <grid:AgDataGrid.TotalSummary>                                     <grid:AgDataGridSummaryItem FieldName="Address" SummaryType="Count" Title="Matches Found" />                                 </grid:AgDataGrid.TotalSummary>                             </grid:AgDataGrid> 

Answers & Comments...

Answer: 1

The exception tells

Set property 'System.Windows.FrameworkElement.Style' threw an exception.

Though this is not in the code you displayed - but I am almost sure you will find something like this somewhere in your code:

<SomeControl Style="MyCoolStyle" ... /> 

where it should be:

<SomeControl Style="{StaticResource MyCoolStyle}" ... /> 
by : Spontifixushttp://stackoverflow.com/users/1521227




Include the templated Control into template?

Include the templated Control into template?

I want to template a Control and include the Control itself into the template, not only the control's content.

For example, I have a button:

<Grid x:Name="LayoutRoot" Background="White">          <Button Name="hello" Content="123" Width="100" Height="100" >         </Button>  </Grid> 

I want to make a broader to surround this button, so it will look like this:

<Grid x:Name="LayoutRoot" Background="White" Width="120" Height="120">          <Rectangle Fill="AliceBlue"/>         <Button Name="hello"  Content="123" Width="100" Height="100" >         </Button>  </Grid> 

But I want to make this more genric, not only for button, but for some other control. i.e Image, TreeViewItem etc.

So I created a template:

<UserControl.Resources>      <Style TargetType="Button">         <Setter Property="Template">             <Setter.Value>                 <ControlTemplate TargetType="Button">                     <Grid Width="120" Height="120">                         <Rectangle Fill="AliceBlue"/>                                                     <ContentPresenter  Content="{TemplateBinding Property=ContentControl.Content}" />                     </Grid>                 </ControlTemplate>             </Setter.Value>         </Setter>     </Style> </UserControl.Resources> <Grid x:Name="LayoutRoot" Background="White">          <Button Name="hello"  Content="123" Width="100" Height="100" >         </Button> </Grid> 

Now the ContentPresenter only display the content of the Button, but not include the button itself, how can I include the templated control itself too?

Answers & Comments...




Why does Unsubscribing DataContextChanged Causes InvalidOperation Exception due to Collection Modified

Why does Unsubscribing DataContextChanged Causes InvalidOperation Exception due to Collection Modified

I recently stumbled across an issue in silverlight with using the datacontext changed event.

If you subscribe to a changed event and then immediately unsubscribe it will throw an exception,

DataContextChanged += MainPage_DataContextChanged; void MainPage_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) {   var vm = e.NewValue as VM;   if(vm != null)   {      DataContextChange-= MainPage_DataContextChanged;//throws invalidoperationexception for collection modified   } } 

to fix this I just unsubscribe the event later, in this situation the requirement is to unsubscribe sooner rather than later so this works.

DataContextChanged += MainPage_DataContextChanged; void MainPage_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) {   var vm = e.NewValue as VM;   if(vm != null)   {       //forces item onto the dispatcher queue so anything needing to happen with 'collections' happens first       Dispatcher.BeginInvoke(()=>         {      DataContextChange-= MainPage_DataContextChanged;//throws invalidoperationexception for collection modified          });   } } 

I'm guessing the collections are the Child elements of all the different controls in the visual tree, and I'm guessing their updates are probably happening on the dispatcher queue so my question is this:

Why does the event being unsubscribed after it has fired affect collections that are going to be modified or updated after this?

EDIT: After giving this some thought Could this have anything to do with the event handlers invocation list being modified before its finished?

Answers & Comments...

Answer: 1

Your suspicions about the invocation list being modified are correct.

Here is the code that fires the DataContextChanged event, according to dotPeek's decompilation:

private void RaisePublicDataContextChanged() {   if (this._dataContextChangedInfo == null)     return;   object oldValue = this._dataContextChangedInfo.OldValue;   object dataContext = this.DataContext;   if (oldValue == dataContext)     return;   this._dataContextChangedInfo.OldValue = dataContext;   List<DependencyPropertyChangedEventHandler>.Enumerator enumerator = this._dataContextChangedInfo.ChangedHandlers.GetEnumerator();   try   {     // ISSUE: explicit reference operation     while (((List<DependencyPropertyChangedEventHandler>.Enumerator) @enumerator).MoveNext())     {       // ISSUE: explicit reference operation       ((List<DependencyPropertyChangedEventHandler>.Enumerator) @enumerator).get_Current()((object) this, new DependencyPropertyChangedEventArgs(FrameworkElement.DataContextProperty, oldValue, dataContext));     }   }   finally   {     enumerator.Dispose();   } } 

As you can see, the code is using an enumerator to iterate through the collection of handlers. So when you unsubscribe from the event during the invocation of a handler, you are invalidating the enumerator, causing the exception you are seeing.

by : Marty Dillhttp://stackoverflow.com/users/184630




How to Set Design Time Sizes and Positions for a Control in Silverlight

How to Set Design Time Sizes and Positions for a Control in Silverlight

I'm wondering if there is a simple way to set the design time sizes and positions for a control in Silverlight.

For example, there is a TextBlock on the canvas which is the LayoutRoot. I want to set the TextBlock's design-time Width, Height, Canvas.Left, and Canvas.Top. (NOTE: the run-time Width, Height, Canvas.Left, and Canvas.Top will be bound with a dynamic property in XAML (not in code).

Answers & Comments...

Answer: 1

You can specify the DesignHeight and DesignWidth properties. But as far as I can tell, the others are not possible.

To get the width and height, make sure the xmlns for the design properties is brought in

xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 

Then, you can use it like so.

<TextBox d:DesignWidth="250" d:DesignHeight="75" /> 

Hope that helps!

by : mw007http://stackoverflow.com/users/1327477




Friday, September 21, 2012

DataBinding in WrapPanel ?

DataBinding in WrapPanel ?

In a WrapPanel if controls are hard-coded in xaml then it is aligned according to spaces available in the panel . that takes no extra efforts to align the controls.
But how to achieve the same behaviour if those controls are dynamically generated i.e., come through data binding ?
e.g.,
<wrapPanel>
  <checkbox ....>
  <checkbox ....>
  <checkbox ....>
  <checkbox ....>
  <checkbox ....>
  <checkbox ....>
<wrapPanel>

For above code it is aligned according to the spaces available . That's fine .
But how to achieve the same layout if these checkbox are generated through a DataTemplate to populate from binding .

Answers & Comments...

Answer: 1

This will more clearly explain my intension :

<controls:WrapPanel Width="200" >                  <ItemsControl ItemsSource="{Binding Info}" >                      <ItemsControl.ItemTemplate>                          <DataTemplate>                              <TextBlock Text="{Binding Name}" Width="50" HorizontalAlignment="Left"></TextBlock>                          </DataTemplate>                      </ItemsControl.ItemTemplate>                  </ItemsControl>  </controls:WrapPanel>  



All the controls are stacked vertically though there are plenty of spaces available . This works fine if binding is not used and static controls are written in the markup . But what is happening if DataBinding is done ?

Can anyone help please ?



Answer: 2

Any resolution team members ?



Answer: 3

Is it not possible ?



Answer: 4
Yes, you need to set the ItemsPanel to a WrapPanel like so:  
 
<Grid x:Name="LayoutRoot" Background="White">          <Grid.Resources>              <ItemsPanelTemplate x:Name="WrapItems">                  <tk:WrapPanel />              </ItemsPanelTemplate>          </Grid.Resources>            <ItemsControl ItemsSource="{Binding Info}" ItemsPanel="{StaticResource WrapItems}" >              <ItemsControl.ItemTemplate>                  <DataTemplate>                      <TextBlock Text="{Binding FullName}" Width="50" HorizontalAlignment="Left"></TextBlock>                  </DataTemplate>              </ItemsControl.ItemTemplate>          </ItemsControl>      </Grid>



Answer: 5

YES! that did. But can you please tell me where i was lacking or what should i study to resolve these types of problems ?

You did it for me , but what is my weak point ? Can you just take a minute to tell me ?