How to add mouse click event on Push pins in Bing map metro app using C# and Xml? - microsoft-metro

I have a multiple dynamic push pins on bing map. I want to add a mouse click event on these push pin. Tell me how can i do it. I am working in windows store app using C# and XML.

When you are adding pushpins programmatically, add common event handler Tapped to each pushpin. When pushpin is tapped it will be called and from sender object you can differentiate each push pin and do whatever you like.
//Suppose I have PushpinsCollection which is list of MyPushpin class. PushpinsCollection is generated dynamically
public class MyPushpin
{
public int PinID { get; set; }
public Pushpin Pin { get; set; }
public Location PinLocation { get; set; }
}
//run foreach loop do add event hanlder and add to map
//Here MyMap is Bing Map control
foreach(var pushpin in PushpinsCollection)
{
var _pin = pushpin.Pin;
_pin.Tapped += Pushpin_Tapped
MapLayer.SetPosition(_pin, PinLocation);
MyMap.Children.Add(_pin);
}
private void Pushpin_Tapped(object sender, TappedRoutedEventArgs e)
{
var TappedPin = (Pushpin)sender;
//TODO: do whatever opetraion you want to with TappedPin
}

Related

MVC 4 Add a child record to existing parent

How do you add a child to a parent record in MVC 4 using EF?
I've got a grid showing News. I need to add Updates that are children records of those. One DB table has News, another has Updates. They are linked by NewsID in each table.
NEWS MODEL
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int NewsId { get; set; }
public string Body { get; set; }
//other fields
UPDATES MODEL
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int NewsUpdateId { get; set; }
public int NewsId { get; set; }
public string Body { get; set; }
//other fields
NEWS INDEX VIEW (only partly posted here; it's a grid showing these detail rows)
#foreach (var item in Model) {
<tr>
<td>#Html.ActionLink(item.Headline, "Details", new { id=item.NewsId })</td>
<td>#Html.Raw(item.Body.Remove(300))...</td>
//other fields
<td>#Html.ActionLink("Edit", "Edit", new { id=item.NewsId })</td>
//WOULD LIKE ANOTHER LINK GOING TO "UPDATE" SCREEN TO ADD CHILD UPDATES, PASSING IN THE PARENT ID
</tr>
}
CONTROLLER (right now)
public ActionResult Update()
{
return View();
}
But of course when I'm on that Update screen and save, there's no NewsID to save into Updates and it fails. How can I pass NewsID from the index screen/grid into my "Create Update" screen, then later retrieve it while on that Update screen and add it to my save action?
UPDATE
Since no one has any idea how to do this, I'm making it up as I go along without luck.
I've tried using the NewsUpdate screen like an Edit where you pass the id value. The difference is that, for Edit, you're editing that record. For this NewsUpdate, I'm adding a NewsUpdate, which is a child record of News, so I have the existing NewsID and need to pass it to my NewsUpdate screen and ultimately use it to set NewsUpdate.NewsID to it.
When I save the NewsUpdate screen, the model is invalid because it is missing, so I tried to this to set it:
var NewsID = Request.Url.PathAndQuery.ToString(); //grab it from url News/Update/8
NewsID = NewsID.Replace("/News/Update/", ""); //results in NewsID = 8
NewsUpdate.NewsID = Convert.ToInt32(NewsID);
This works, but the model is still invalid right after this. So this is no good.
Got it.
public ActionResult Update(int id = 0)
{
NewsUpdate myUpdate= db.NewsUpdate.Create(); //create empty child model
myUpdate.NewsID = id; //set my parent's ID on the child model
View(myUpdate); //send child model to child's create screen aka "NewsUpdate"
}
This passes my parent id in the child model and the rest of the NewsUpdate screen, which is like a standard Create screen, just functions as usual.

EF 5.0 Code First Winforms Combobox Data Binding

I'm trying to bind some lookup tables to comboboxes on winforms. I've built the POCCO classes and generated the database. I've added the data source to my app. I drop the source tables onto the comboboxes in the designer and the binding gets set up fine for each. I've populated the tables in the db with test data.
Here's where I need help. With datasets I would simply do a tableadapter fill on the form Load event to get the data. With EF I must have to do something to load the data. Perhaps a query? Something else? I bleieve everything is set up correctly. Just need the final step to get it to load and work. Thanks.
There are many ways how to communicate with your database. I understood, you are probably using EF Code First approach. Imagine this context:
public class WinFormContext : DbContext
{
public DbSet<Car> Cars { get; set; }
}
public class Car
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
You are gonna add some record first. You create simple form with textboxs and one button.
private void button1_Click(object sender, EventArgs e)
{
using (var WinFormContext = new WinFormContext())
{
Car car = new Car { Name = textBox1.Text };
WinFormContext.Cars.Add(car);
WinFormContext.SaveChanges();
}
}
It is simple solution, how to add new record after onClick event. Now you want to show all record in Grid View. One of the possible solution is fill the controll manually:
BindingSource bindingSource = new BindingSource();
private void Form2_Load(object sender, EventArgs e)
{
var WinFormContext = new WinFormContext();
bindingSource.DataSource = WinFormContext.Cars.ToList();
dataGridView1.DataSource = bindingSource;
dataGridView1.AutoGenerateColumns = true;
}
But there is more ways how to do it. I recommend you take a look on "data binding in win forms" on Google...

How can I marry AutoCompleteBox.PopulateComplete method with the MVVM paradigm?

Here is the setup:
I have an autocompletebox that is being populated by the viewmodel which gets data from a WCF service. So it's quite straightforward and simple so far.
Now, I am trying to follow the principles of MVVM by which the viewmodel doesn't know anything about the view itself. Which is good, because I bound the Populating event of the autocomplete box to a method of my viewmodel via triggers and commands.
So the view model is working on fetching the data, while the view is waiting. No problems yet.
Now, the view model got the data, and I passed the collection of results to a property bound to the ItemSource property of the control. Nothing happens on the screen.
I go to MSDN and to find the officially approved way on how this situation is supposed to be handled (http://msdn.microsoft.com/en-us/library/system.windows.controls.autocompletebox.populating(v=vs.95).aspx):
Set the MinimumPrefixLength and MinimumPopulateDelay properties to
values larger than the default to minimize calls to the Web service.
Handle the Populating event and set the PopulatingEventArgs.Cancel
property to true.
Do the necessary processing and set the ItemsSource property to the
desired item collection.
Call the PopulateComplete method to signal the AutoCompleteBox to show
the drop-down.
Now I see a big problem with the last step because I don't know how I can call a method on a view from the view model, provided they don't know (and are not supposed to know!) anything about each other.
So how on earth am I supposed to get that PopulateComplete method of view called from the view model without breaking MVVM principles?
If you use Blend's Interactivity library, one option is an attached Behavior<T> for the AutoCompleteBox:
public class AsyncAutoCompleteBehavior : Behavior<AutoCompleteBox>
{
public static readonly DependencyProperty SearchCommandProperty
= DependencyProperty.Register("SearchCommand", typeof(ICommand),
typeof(AsyncAutoCompleteBehavior), new PropertyMetadata(null));
public ICommand SearchCommand
{
get { return (ICommand)this.GetValue(SearchCommandProperty); }
set { this.SetValue(SearchCommandProperty, value); }
}
protected override void OnAttached()
{
this.AssociatedObject.Populating += this.PopulatingHook;
}
protected override void OnDetaching()
{
this.AssociatedObject.Populating -= this.PopulatingHook;
}
private void PopulatingHook(object sender, PopulatingEventArgs e)
{
var command = this.SearchCommand;
var parameter = new SearchCommandParameter(
() => this.AssociatedObject
.Dispatcher
.BeginInvoke(this.AssociatedObject.PopulateComplete),
e.Parameter);
if (command != null && command.CanExecute(parameter))
{
// Cancel the pop-up, execute our command which calls
// parameter.Complete when it finishes
e.Cancel = true;
this.SearchCommand.Execute(parameter);
}
}
}
Using the following parameter class:
public class SearchCommandParameter
{
public Action Complete
{
get;
private set;
}
public string SearchText
{
get;
private set;
}
public SearchCommandParameter(Action complete, string text)
{
this.Complete = complete;
this.SearchText = text;
}
}
At this point you need to do 2 things:
Wire up the Behavior
<sdk:AutoCompleteBox MinimumPopulateDelay="250" MinimumPrefixLength="2" FilterMode="None">
<i:Interaction.Behaviors>
<b:AsyncAutoCompleteBehavior SearchCommand="{Binding Search}" />
</i:Interaction.Behaviors>
</sdk:AutoCompleteBox>
Create a DelegateCommand which handles your aysnc searching.
public class MyViewModel : ViewModelBase
{
public ICommand Search
{
get;
private set;
}
private void InitializeCommands()
{
this.Search = new DelegateCommand<SearchCommandParamater>(DoSearch);
}
private void DoSearch(SearchCommandParameter parameter)
{
var client = new WebClient();
var uri = new Uri(
#"http://www.example.com/?q="
+ HttpUtility.UrlEncode(parameter.SearchText));
client.DownloadStringCompleted += Downloaded;
client.DownloadStringAsync(uri, parameter);
}
private void Downloaded(object sender, DownloadStringCompletedEventArgs e)
{
// Do Something with 'e.Result'
((SearchCommandParameter)e.UserState).Complete();
}
}

Understanding Forms in MVC: How can I populate the model from a List<>

Conclusion in Images, can be found in the bottom
I'm having some trouble to get how Forms work in MVC (as I'm a WebForms Developer and really wanna start using MVC in one big project)
I took the MVC2 Web Project and add a simple ViewModel to it
namespace TestForms.Models
{
public class myFormViewModel
{
public myFormViewModel() { this.Options = new List<myList>(); }
public string Name { get; set; }
public string Email { get; set; }
public List<myList> Options { get; set; }
}
public class myList
{
public myList() { this.Value = this.Name = ""; this.Required = false; }
public string Name { get; set; }
public string Value { get; set; }
public string Type { get; set; }
public bool Required { get; set; }
}
}
Created a Strongly Typed View, passed a new object to the view and run it.
When I press submit, it does not return what's in the Options part... how can I bind that as well?
my view
alt text http://www.balexandre.com/temp/2010-10-11_1357.png
filling up the generated form
alt text http://www.balexandre.com/temp/2010-10-11_1353.png
when I press Submit the Options part is not passed to the Model! What am I forgetting?
alt text http://www.balexandre.com/temp/2010-10-11_1352.png
Conclusion
Changing the View loop to allocate the sequential number, we now have
<%= Html.TextBox("model.Options[" + i + "].Value", option.Value)%>
model is the name of our Model variable that we pass to the View
Options is the property name that is of type List
and then we use the property name
Looking at your UI it seems that you did not put the data from the Options member on it.
<% foreach (myList obj in Model.Options) { %>
// Add the object to your UI. they will be serialized when the form is submitted
<% } %>
Also check that you enclose the data in a form element
EDIT:
Sorry! I did'nt realized that you was filling the object inside the controller. Can you please show the code you have in the view?

MVVM - Deciding which ViewModel is responsible for what

I have a simple app that consists of:
Model
Items
Filter criteria applied to that list of items
Views
WelcomePage
MainItemsPage
FilterEditPage
I am using MVVM Light and Windows Phone 7
I currently have 3 ViewModels, one for each View. In the past I have had a single ViewModel which made the comunication which I am about to ask about very easy. However I wanted to go with the 3 seperate VMs as that seems to be the correct way.
The WelcomePage is able to set one of the Filter criteria before navigating to the MainItemsPage. The MainItemsPage is bound to an Items property that is exposed by its ViewModel. That ViewModel needs to have filtered that list depending on the current filter criteria. The FilterEditPage allows the user to edit the full criteria set of 4 variables. When the criteria is changed the Items collection used in the ViewModel for MainItemsPage needs to be refiltered.
The question is how I flow the Filter changes through the app. I know that MVVM has the concept of Messaging and the MVVM Light toolkit provides the Messenger class. However what I am struggling with is where does the responsibility lie for sending those messages?
Do the 3 VMs go to the Model whenever they need to work with the current Filter set?
Do all Filter updates go through the FilterEditViewModel and that in turn broadcasts a filter change message?
Do I go back to a single VM for all the Views?
I cannot see 1. working because something will need to trigger the VMs to go back to the Model
I know I can get 3. working right now with no problem. Is it that wrong?
TIA
Pat Long
I would put the shared current filter in the Model not the view model. You've got lots viewModels potentially on different pages or on the same page (consider a breadcrumb showing current selection and something else that needs to show a filter has been applied).
How about a singleton model for the Filter that view models can subscribe to?
Three VMs is the right way in your scenario. I suggest you to build a Parent/Child relation between you VMs. Since the the MainVM holds the ItemList, this is the place, where FilterChanges are applied. The FilterEditVM only receives the filter changes and than calls the MainVM, that it has to re-apply the filters.
The structure would be something like this:
public class WelcomePageVM
{
public WelcomePageVM()
{
this.FilterEditPageVM = new FilterEditPageVM(this);
this.MainItemsVM = new MainItemsVM(this);
}
public FilterEditPageVM FilterEditPageVM { get; private set; }
public MainItemsVM MainItemsVM { get; private set; }
public void SetInitialFilter1(object filter)
{
// the initial filter
this.FilterEditPageVM.Filter1Value = filter;
this.MainItemsVM.ApplyFilters();
}
}
public class FilterEditPageVM : ChildViewModelBase<WelcomePageVM>
{
public FilterEditPageVM(WelcomePageVM parent)
: base(parent) { }
public object Filter1Value { get; set; }
public object Filter2Value { get; set; }
public object Filter3Value { get; set; }
public object Filter4Value { get; set; }
public void FinishFilterChange()
{
this.Parent.MainItemsVM.ApplyFilters();
}
}
public class MainItemsVM : ChildViewModelBase<WelcomePageVM>
{
public MainItemsVM(WelcomePageVM parent)
: base(parent) { }
public List<object> ItemList { get; set; }
public void ApplyFilters()
{
// filter apply logic
}
}
public abstract class ChildViewModelBase<T>
{
T _parent;
public ChildViewModelBase(T parent)
{
this._parent = parent;
}
public T Parent { get { return _parent; } }
}
Here you can access all viewmodels, which is okay because you stay in the "controller" level.