WP7 - Is it possible to selecte the item from list on button click time - xaml

I want to select the list item when I click the button(Which is inside the list box for every row).
Now I have try like this:-
<ListBox Height="444"
ItemsSource="{Binding StudentDetails,Mode=TwoWay}"
HorizontalAlignment="Left" Margin="2,34,0,0"
Name="listBox1" VerticalAlignment="Top"
Width="476" BorderBrush="#00410D0D"
SelectedIndex="{Binding MemberPrivacy,Mode=TwoWay}"
SelectedItem="{Binding SelectedStudent, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Gray" Padding="5" BorderThickness="1">
<StackPanel Orientation="Horizontal">
<Border BorderBrush="Wheat" BorderThickness="1">
<Image Name="ListPersonImage" Source="{Binding PersonImage}" Height="100" Width="100" Stretch="Uniform" Margin="10,0,0,0"/>
</Border>
<TextBlock Text="{Binding FirstName}" Name="firstName" Width="200" Foreground="White" Margin="10,10,0,0" FontWeight="SemiBold" FontSize="22" />
<Image Height="50" Source="{Binding addImage}" HorizontalAlignment="Left" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="50" />
<Button Margin="-100,0,0,0" Height="80" Width="80" DataContext="{Binding DataContext, ElementName=listBox1}" Command="{Binding addPerson}" >
<Button.Background>
<ImageBrush ImageSource="{Binding addImage, Converter={StaticResource pathToImageConverter}}" Stretch="Fill" />
</Button.Background>
</Button>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
My View Model:-
public ListBoxEventsViewModel()
{
addPerson = new ReactiveAsyncCommand();
addPerson.Subscribe(x =>
{
MessageBox.Show("Test Button Selected..");
});
}
Here I can show the message box when I click the button. But I can not select the list item. Please let me know to solve this problem.
Thanks in advance.
View Model:-
List box selected Item:-
public ListBoxEventsModel _SelectedStudent;
public ListBoxEventsModel SelectedStudent
{
get { return _SelectedStudent; }
set
{
this.RaiseAndSetIfChanged(x => x.SelectedStudent, value);
MessageBox.Show("Selected index==>" + SelectedStudent.FirstName);
}
}
Here it showing the selected name when I click the list item. But this same thing I want to write it for the button(addImage)

Bind the SelectedItem on the ListBox to a "SelectedItem" property on the ViewModel.
eg SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
then on the view model just add a property of SelectedItem, then you can just set that from in your subscribe.

Related

How to prevent multiple click on tab for focusing on AutoSuggestBoxView?

I have a Form in which there are many labels and textfield. So I'm navigating within the textfield or entry by clicking on tab button in my keyboard. The normal entry is getting focused on single click whereas the AutoSuggestBoxView which is a custom entry needs two clicks on tab to get focused. I don't know why I'm facing this issue. I have applied tabindex as 0 and -1 but still it is not working.This is my xaml code
<CtrlUC:UCCurrentLocation Grid.Row="0" HeightRequest="32" Grid.Column="0" Latitude="{Binding FieldsData.fromlatitude.Value,Mode=TwoWay}" Longitude="{Binding FieldsData.fromlongitude.Value,Mode=TwoWay}" Grid.RowSpan="2" Grid.ColumnSpan="2" HorizontalOptions="Fill" VerticalOptions="Fill" WidthRequest="400" Title="Location" LatitudeTitle="Latitude" LongitudeTitle="Longitude" ButtonText="Location" IsEditable="False" IsVisible="{Binding Path=FieldsData.FromLocationControl.IsVisible, Mode=TwoWay}" IsEnabled="{Binding Path=FieldsData.IsViolationCreated.IsEnabled, Mode=TwoWay}" />
<local:AutoSuggestBoxView x:Name="FromState" Grid.Row="1" Grid.Column="2" TabIndex="-1" Grid.RowSpan="1" Grid.ColumnSpan="1" DisplayMemberPath="{Binding FieldsData.PickerFromState.Value.DisplayField}" SelectedValuePath="{Binding FieldsData.PickerFromState.Value.ValueField}" SearchMemberPath="{Binding FieldsData.PickerFromState.Value.DisplayField}" VerticalOptions="StartAndExpand" ItemsSource="{Binding Path=FieldsData.PickerFromState.Value.DataSource}" SelectedItem="{Binding Path=FieldsData.PickerFromStateSelectedItem.Value, Mode=TwoWay}" SelectedValue="{Binding Path=FieldsData.fromstatePropertyText.Value, Mode=TwoWay}" Text="{Binding Path=FieldsData.fromstatename.Value, Mode=TwoWay}" Placeholder="Enter State" IsEnabled="{Binding Path=FieldsData.IsViolationCreated.IsEnabled, Mode=TwoWay}" IsVisible="{Binding Path=FieldsData.PickerFromState.IsVisible, Mode=TwoWay}" />
<local:CCEntry Grid.Row="1" Grid.Column="3" Style="{StaticResource FormEntryStyle}" Margin="0,0,10,3" Text="{Binding Path=FieldsData.fromstatecode.Value, Mode=TwoWay}" Grid.RowSpan="1" Grid.ColumnSpan="1" HorizontalOptions="Fill" VerticalOptions="Fill" IsEnabled="{Binding Path=FieldsData.fromstatecode.IsEnabled, Mode=TwoWay}" IsVisible="{Binding Path=FieldsData.LblFromStateCodeValue.IsVisible, Mode=TwoWay}" />
<local:AutoSuggestBoxView x:Name="FromCity" Grid.Row="1" Grid.Column="4" TabIndex="" Grid.RowSpan="1" Grid.ColumnSpan="1" DisplayMemberPath="{Binding FieldsData.PickerFromCity.Value.DisplayField}" SelectedValuePath="{Binding FieldsData.PickerFromCity.Value.ValueField}" SearchMemberPath="{Binding FieldsData.PickerFromCity.Value.DisplayField}" VerticalOptions="StartAndExpand" ItemsSource="{Binding Path=FieldsData.PickerFromCity.Value.DataSource}" SelectedItem="{Binding Path=FieldsData.PickerFromCitySelectedItem.Value, Mode=TwoWay}" SelectedValue="{Binding Path=FieldsData.fromcityPropertyText.Value, Mode=TwoWay}" Text="{Binding Path=FieldsData.fromcityname.Value, Mode=TwoWay}" Placeholder="Enter City" IsEnabled="{Binding Path=FieldsData.IsViolationCreated.IsEnabled, Mode=TwoWay}" IsVisible="{Binding Path=FieldsData.PickerFromCity.IsVisible, Mode=TwoWay}" />
<local:CCEntry Grid.Row="1" Grid.Column="5" Style="{StaticResource FormEntryStyle}" Margin="0,0,10,3" Text="{Binding Path=FieldsData.fromcitycode.Value, Mode=TwoWay}" Grid.RowSpan="1" Grid.ColumnSpan="1" HorizontalOptions="Fill" VerticalOptions="Fill" IsEnabled="{Binding Path=FieldsData.fromstatecode.IsEnabled, Mode=TwoWay}" IsVisible="{Binding Path=FieldsData.LblFromCityCodeValue.IsVisible, Mode=TwoWay}" />
<local:AutoSuggestBoxView x:Name="FromCounty" Grid.Row="1" Grid.Column="6" TabIndex="0" Grid.RowSpan="1" Grid.ColumnSpan="1" DisplayMemberPath="{Binding FieldsData.PickerFromcounty.Value.DisplayField}" SelectedValuePath="{Binding FieldsData.PickerFromcounty.Value.ValueField}" SearchMemberPath="{Binding FieldsData.PickerFromcounty.Value.DisplayField}" VerticalOptions="StartAndExpand" ItemsSource="{Binding Path=FieldsData.PickerFromcounty.Value.DataSource}" SelectedItem="{Binding Path=FieldsData.PickerFromCountySelectedItem.Value, Mode=TwoWay}" SelectedValue="{Binding Path=FieldsData.fromcountyPropertyText.Value, Mode=TwoWay}" Text="{Binding Path=FieldsData.fromcountyname.Value, Mode=TwoWay}" Placeholder="Enter County" IsEnabled="{Binding Path=FieldsData.IsViolationCreated.IsEnabled, Mode=TwoWay}" IsVisible="{Binding Path=FieldsData.PickerFromcounty.IsVisible, Mode=TwoWay}" />
<local:CCEntry Grid.Row="1" Grid.Column="7" Style="{StaticResource FormEntryStyle}" Margin="0,0,10,3" Text="{Binding Path=FieldsData.fromcountycode.Value, Mode=TwoWay}" Grid.RowSpan="1" Grid.ColumnSpan="1" HorizontalOptions="Fill" VerticalOptions="Fill" IsEnabled="{Binding Path=FieldsData.fromstatecode.IsEnabled, Mode=TwoWay}" IsVisible="{Binding Path=FieldsData.LblFromCountyCodeValue.IsVisible, Mode=TwoWay}" />
So as you can see in code the normal entry like CCEntry takes only one tab click. But the custom entry AutoSuggestBoxView takes two clicks on tab to get focused.I have no clue how to fix this. Any suggestions?
There is only one way to avoid multiple clicks in xamarin.forms is you have to use a boolean flag as shown below
public class MyPage : ContentPage
{
public isClicked = false;
public MyPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
isClicked = false;
}
private void ItemTapped(object sender, System.EventArgs e)
{
if(isClicked)
return;
isClicked = true;
//Do your work here
}
}
I am using this way to avoid multiple clicks.

Sending SelectedIndex of ListView to ViewModel through CommandParameter

after a quite bit of googling I haven't found answer on this problem.
I have this ListView
<ListView x:Name="itemListView" ItemsSource="{Binding History}" HorizontalAlignment="Stretch">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate>
<Border Style="{StaticResource Border}" Background="{ThemeResource GradientLinear}" HorizontalAlignment="Stretch">
<Grid>
<StackPanel Orientation="Vertical" Margin="10,10,10,10" HorizontalAlignment="Left" Grid.Row="0" Grid.Column="0">
<TextBlock Text="{Binding name}" />
<TextBlock Text="{Binding question}" TextWrapping="Wrap"/>
<TextBlock Text="{Binding vrijeme}"/>
</StackPanel>
<Button Width="50" Height="50" Opacity="0.6" Grid.Row="0" Grid.Column="1" Tag="{Binding name}"
Command="{Binding ElementName=itemListView, Path=DataContext.Delete}" CommandParameter="{Binding ElementName=itemListView, Path=SelectedIndex}"
HorizontalAlignment="Right">
<SymbolIcon
HorizontalAlignment="Center"
Width="48"
Height="48"
Symbol="Delete" />
</Button>
</Grid>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Problem is probably in this part of the code
<Button Width="50" Height="50" Opacity="0.6" Grid.Row="0" Grid.Column="1" Tag="{Binding name}"
Command="{Binding ElementName=itemListView, Path=DataContext.Delete}" CommandParameter="{Binding ElementName=itemListView, Path=SelectedIndex}"
HorizontalAlignment="Right">
When I click Button, ListViewItem that contains that Button is not selected so I get -1 for SelectedIndex or just null if I target SelectedItem. It seems that clicking that button leaves containing ListViewItem unaffected. If I first click ListViewItem and than click button it works, SelectedItem is set in ListView of course, but I can't count user will understand that. My question is - is there any way to "force" Button to send me in CommandArgument SelectedItem or SelectedIndex. I know how to do that through code-behind but I am interested in solving this problem through MVVM.
Thanx in advance.

UWP - How to bind a ContentPresenter's element to the main ViewModel?

I work on an app where the user can edit a "big" form:
The form contains a lot of fields: it is displayed in a Pivot, where each PivotItem represents a category of the form.
Some categories contain one or more child items: they are displayed through a Master-Detail presentation.
To display the items of the Detail part, I use a ContentPresenter that is binded directly to the Model:
<ContentPresenter
x:Name="DetailContentPresenter"
Grid.Column="1"
Grid.RowSpan="2"
BorderThickness="1,0,0,0"
Padding="24,0"
BorderBrush="{ThemeResource SystemControlForegroundBaseLowBrush}"
Content="{x:Bind MasterListView.SelectedItem, Mode=OneWay}">
<ContentPresenter.ContentTemplate>
<DataTemplate x:DataType="models:Form_Parts">
<...>
</DataTemplate>
</ContentPresenter.ContentTemplate>
</ContentPresenter>
This works fine, but there is a "third" level in the main form: a list of photos, that I display in the ContentPresenter through a GridView. This works also great, but I would like to use an "Add" button or the "ItemClick" event to interact with the photos: I don't see how I could bind a Command in the main ViewModel, instead of the ContentPresenter's DataContext. The other fields of this form bind well on this ViewModel.
I did some tests without any result:
<StackPanel Orientation="Horizontal" Grid.Row="1">
<GridView ItemsSource="{Binding images}"
ItemClick="{Binding PhotoClickCommand}">
<GridView.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Gray" BorderThickness="1"
Padding="10"
Height="150" Width="190">
<Image Stretch="UniformToFill"
Source="{Binding bitmap_image}" />
</Border>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
<Border BorderBrush="Gray" BorderThickness="1"
Padding="10"
Height="150" Width="190">
<Button Command="{Binding Path=DataContext.AddPhotoCommand, ElementName=DetailsPage}"
Height="100" Width="100">
<Viewbox>
<SymbolIcon Symbol="Add"/>
</Viewbox>
</Button>
</Border>
</StackPanel>
=> is there a way to doing this?
Edit :
I solved my problem for the "Add" button thanks Alteik with:
<Button Command="{Binding ElementName=Root, Path=DataContext.AddPhotoCommand}" Height="100" Width="100">
But I always get a problem with the ItemClick of the GridView. I tried this:
<GridView ItemsSource="{Binding images}"
IsItemClickEnabled="True"
SelectionMode="None">
<i:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="Tapped">
<core:InvokeCommandAction Command="{Binding ElementName=Root, Path=DataContext.EditPhotoCommand}"
CommandParameter="{Binding Mode=OneWay}"/>
</core:EventTriggerBehavior>
</i:Interaction.Behaviors>
<...>
</GridView>
But I don't get the expected parameter in the ViewModel:
private void EditPhoto(object sender)
{
Images sImage = (Images)sender;
if (sImage != null)
{
NavigationService.NavigateTo<CommentImageViewModel>(this, new Object[] { sImage }, true);
}
}
The sender is the current Form_Parts (the DataTemplate of the ContentPresenter), whereas I would get the selected item of my images collection, that is binded to the GridView...
=> Whad could I do to fix this?
You should be able to change the DataContext in a child element doing this:
Command"{Binding ElementName=Root, Path=DataContext.TheCommandFromRoot}"
Obviously you need to set the name of the parent's element to "Root"

Windows Phone 8 Nokia Maps: How to change the design of a Microsoft.Phone.Maps.Toolkit Pushpin?

Default, they look like this: http://wp.qmatteoq.com/wp-content/uploads/2013/01/map.png. I would like to have them look like on Nokia Maps, like this: http://www.themobileindian.com/images/nnews/2012/11/9225/Nokia-Maps.jpg, so they take less space. And everytime I tap on them, they will toggle between icon and description.
Lets say I have two templates for pushpin in resources:
<ControlTemplate x:Key="1" TargetType="maptk:Pushpin">
<Grid x:Name="ContentGrid" Background="Transparent" Margin="-4,0,0,0">
<StackPanel >
<Grid Background="Black">
<StackPanel Margin="5,5,0,0">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Tap">
<cmd:EventToCommand PassEventArgsToCommand="False"
CommandParameter="{Binding}"
Command="{Binding ElementName=NearbyMap, Path=DataContext.Pushpin_OnTapCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<TextBlock Text="{Binding Location}" Foreground="White" />
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding LocationName}" Foreground="White" />
<TextBlock Text="-" Foreground="White" Padding="3,0"/>
<TextBlock Text="{Binding LocationName}" Foreground="White" />
</StackPanel>
<TextBlock Text="{Binding LocationName}" Foreground="White" />
<TextBlock Text="{Binding LocationName}" Foreground="White" />
</StackPanel>
</Grid>
<Polygon Fill="Black" Points="0,0 29,0 0,29" Width="29" Height="29" HorizontalAlignment="Left" />
<Grid Height="26" Width="26" Margin="-13,-13,0,0" RenderTransformOrigin="0.5,0.5" HorizontalAlignment="Left">
<Grid.RenderTransform>
<CompositeTransform Rotation="-45"/>
</Grid.RenderTransform>
<Rectangle Fill="Black" HorizontalAlignment="Center" Margin="0" Stroke="White" VerticalAlignment="Center" Height="26" Width="26" />
<Ellipse HorizontalAlignment="Center" Height="16" Margin="0" VerticalAlignment="Center" Fill="Green" Width="16" />
</Grid>
</StackPanel>
</Grid>
</ControlTemplate>
<ControlTemplate TargetType="maptk:Pushpin" x:Key="2">
<Grid Height="26" Width="26" Margin="-13,-13,0,0" RenderTransformOrigin="0.5,0.5" >
<Grid.RenderTransform>
<CompositeTransform Rotation="-45"/>
</Grid.RenderTransform>
<Rectangle Fill="Black" HorizontalAlignment="Center" Margin="0" Stroke="White" VerticalAlignment="Center" Height="26" Width="26"/>
<Ellipse HorizontalAlignment="Center" Height="16" Margin="0" VerticalAlignment="Center" Fill="Red" Width="16"/>
</Grid>
</ControlTemplate>
and the pushpin control:
<maptk:Pushpin x:Name="PushPins" GeoCoordinate="{Binding Location}" Visibility="Visible" Content="{Binding LocationName}" Template="{StaticResource 2}"/>
How can I switch between them with some triggers or something?
#Rares found another solution, that works great in my case...
So the general issue here is just, how to switch/change the design when tapping the pushpin.
Well it seems that when you add the pushpins to the map they get their design from the toolkit, but you still are able to change that by setting the Style propery in code!
So if you hook up each pushpin to a pushpin tap event you can just do the following in your code behind of the XAML page:
private void Pushpin_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
((Pushpin)sender).Style = Application.Current.Resources["PushpinStyle"] as Style;
}
Provided you created a PushpinStyle inside a resourcedictionary that has a Pushpin as TargetType.
To be able to reset the design when pushing on another pushpin, I just keep a reference to the pushpin pressed and reset it's style before changing the style of the newly pressed one!
Works great for me...
You can use a general trick to modify the look of TK components. This can be used for nearly all TK components.
All TK components have styles (defined in XAML), these are not settable via code. But you can override the style in your applicatoin (keep in mind, you override the style in general, so if you modify e.g. pushpin styles, all pushpins inside your app will look like that)
A bit more in detail:
a) Get the TK source from https://phone.codeplex.com/sourcecontrol/latest
b) Have a look into Themes/Generic.xaml
c) Next to the last element, you see the style definition for the pushpin.
Starts with:
<!-- Default Style used for Pushpin -->
<Style TargetType="maptk:Pushpin">
...
d) Copy this style (or you can write it from scratch of course) and modify the style to whatever you like
e) Add this modified code snippet to your Application.Resources (e..g. the Application.Resources section in your App.xaml)
Keep in mind, you also need to reference the right TK namespace.
For pushpin, you need to include:
xmlns:maptk="clr-namespace:Microsoft.Phone.Maps.Toolkit"
Now your app uses the locally overriden style for your pushpin.
Btw: Since TK is Ms-PL licensed, keep in mind that there are probably license restrictions if you take the original source code from MSFT.
I personally found it easier to not use the toolkit for pushpins. Instead I wrote a user control "PushPinUC" that I designed how I wanted it. The UserControl subscribes to the Tap event - so I can expand/retract when it's pressed.
You can add user controls to your Map control using the following code.
private void BindPushpins(IEnumerable<PushpinIVM> pushpins)
{
foreach (var pushpin in pushpins)
{
var pushPinUC = new PushpinUC { Pushpin = pushpin };
var mapOverlay = new MapOverlay { GeoCoordinate = pushpin.Location, Content = pushPinUC };
var mapLayer = new MapLayer { mapOverlay };
Map.Layers.Add(mapLayer);
}
}
I found a solution: add only one control template to the pushpins. The stackpanel is the pushpin with the textbox and the grid before the stackpanel is the pushpin without the textbox. The stackpanel is with visibility collapsed. As you can see there are 2 triggers for the tap event, where i just set the visibility of the pushpin with the textbox to visible or collapsed. You can use any image for the pushpins.
<ctrls:BaseUserControl.Resources>
<ControlTemplate x:Key="PushPinTemplate" TargetType="maptk:Pushpin">
<Grid x:Name="ContentGrid" Background="Transparent" Margin="-4,0,0,0">
<Grid Height="40" Width="30" Margin="-13,-13,0,0" RenderTransformOrigin="0.5,0.5" >
<Image Source="/Assets/Images/push1.png" Width="40" Height="40">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Tap">
<cmd:EventToCommand PassEventArgsToCommand="True"
Command="{Binding ElementName=NearbyMap, Path=DataContext.Rectangle_OnTapCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Image>
</Grid>
<StackPanel x:Name="DetailsPanel" Visibility="{Binding Path=Visibility}">
<Grid x:Name="TestGrid" Background="Black">
<StackPanel Margin="5,5,0,0">
<!--TextBlock tap-->
<i:Interaction.Triggers>
<i:EventTrigger EventName="Tap">
<cmd:EventToCommand PassEventArgsToCommand="True"
Command="{Binding ElementName=NearbyMap, Path=DataContext.Pushpin_OnTapCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<TextBlock Text="{Binding LocationName}" Foreground="White" FontSize="25"/>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding StreetName}" Foreground="White" />
<TextBlock Text="{Binding StreetNumber}" Foreground="White" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding DistanceToDisplay}" Foreground="White" />
</StackPanel>
</StackPanel>
</Grid>
<Polygon Fill="Black" Points="0,0 29,0 0,29" Width="29" Height="29" HorizontalAlignment="Left" Visibility="Visible"/>
<Grid Height="40" Width="30" Margin="-13,-13,0,0" RenderTransformOrigin="0.5,0.5" HorizontalAlignment="Left">
<Image Source="/Assets/Images/push2.png" Width="40" Height="40">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Tap">
<cmd:EventToCommand PassEventArgsToCommand="True"
Command="{Binding ElementName=NearbyMap, Path=DataContext.Rectangle_OnTapCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Image>
</Grid>
</StackPanel>
</Grid>
</ControlTemplate>
</ctrls:BaseUserControl.Resources>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<maps:Map x:Name="NearbyMap"
Center="{Binding MapCenter, Mode=TwoWay}"
ZoomLevel="15"
dp:MapPushPinDependency.ItemsSource="{Binding Path=Locations, Mode=OneWay}"
>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Tap">
<cmd:EventToCommand PassEventArgsToCommand="True"
Command="{Binding ElementName=NearbyMap, Path=DataContext.Map_OnTapCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<maptk:MapExtensions.Children>
<maptk:MapItemsControl Name="StoresMapItemsControl">
<maptk:MapItemsControl.ItemTemplate>
<DataTemplate>
<maptk:Pushpin x:Name="PushPins" GeoCoordinate="{Binding Location}" Visibility="Visible" Content="{Binding LocationName}" Template="{StaticResource PushPinTemplate}"/>
</DataTemplate>
</maptk:MapItemsControl.ItemTemplate>
</maptk:MapItemsControl>
<maptk:UserLocationMarker x:Name="UserLocationMarker" Visibility="Visible" GeoCoordinate="{Binding MyLocation}"/>
</maptk:MapExtensions.Children>
</maps:Map>
</Grid>
#Depechie
private void RectangleTapAction(GestureEventArgs e)
{
var pushpinControl = TryFindParent<Pushpin>(e.OriginalSource as UIElement);
var pushpin = (pushpinControl as FrameworkElement).DataContext as PushPinModel;
Locations.Where(t => t.Id != pushpin.Id).ToList().ForEach(t => t.Visibility = Visibility.Collapsed);
pushpin.Visibility = pushpin.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
e.Handled = true;
}
Locations is an ObservableCollection and there is a Linq where I hide the textbox for other pushpins. PushPinModel has an attribute representing the visibility.

Silverlight- DataGrid control - Selection Changed event interfering with sorting

I'm currently playing with the Silverlight(Beta 2) Datagrid control. Before I wired up the SelectionChanged event, the grid would sort perfectly by clicking on the header. Now, when the grid is clicked, it will fire the SelectionChanged event when I click the header to sort. Is there any way around this?
In a semi-related topic, I'd like to have the SelectionChanged event fire when I click on an already selected item (so that I can have a pop-up occur to allow the user to edit the selected value). Right now, you have to click on a different value and then back to the value you wanted in order for it to pop up. Is there another way?
Included is my code.
The Page:
<UserControl x:Class="WebServicesApp.Page"
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
Width="1280" Height="1024" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" x:Name="OurStack" Orientation="Vertical" Margin="5,5,5,5">
<ContentControl VerticalAlignment="Center" HorizontalAlignment="Center">
<StackPanel x:Name="SearchStackPanel" Orientation="Horizontal" Margin="5,5,5,5">
<TextBlock x:Name="SearchEmail" HorizontalAlignment="Stretch" VerticalAlignment="Center" Text="Email Address:" Margin="5,5,5,5" />
<TextBox x:Name="InputText" HorizontalAlignment="Stretch" VerticalAlignment="Center" Width="150" Height="Auto" Margin="5,5,5,5"/>
<Button x:Name="SearchButton" Content="Search" Click="CallServiceButton_Click" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" Height="Auto" Background="#FFAFAFAF" Margin="5,5,5,5"/>
</StackPanel>
</ContentControl>
<Grid x:Name="DisplayRoot" Background="White" ShowGridLines="True"
HorizontalAlignment="Center" VerticalAlignment="Center" MaxHeight="300" MinHeight="100" MaxWidth="800" MinWidth="200"
ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible">
<data:DataGrid ItemsSource="{Binding ''}" CanUserReorderColumns="False" CanUserResizeColumns="False"
AutoGenerateColumns="False" AlternatingRowBackground="#FFAFAFAF" SelectionMode="Single"
HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5,5,5,5" x:Name="IncidentGrid" SelectionChanged="IncidentGrid_SelectionChanged">
<data:DataGrid.Columns>
<data:DataGridTextColumn DisplayMemberBinding="{Binding Address}" Header="Email Address" IsReadOnly="True" /> <!--Width="150"-->
<data:DataGridTextColumn DisplayMemberBinding="{Binding whereClause}" Header="Where Clause" IsReadOnly="True" /> <!--Width="500"-->
<data:DataGridTextColumn DisplayMemberBinding="{Binding Enabled}" Header="Enabled" IsReadOnly="True" />
</data:DataGrid.Columns>
</data:DataGrid>
</Grid>
</StackPanel>
<Grid x:Name="EditPersonPopupGrid" Visibility="Collapsed">
<Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Opacity="0.765" Fill="#FF8A8A8A" />
<Border CornerRadius="30" Background="#FF2D1DCC" Width="700" Height="400" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="1,1,1,1" BorderBrush="#FF000000">
<StackPanel x:Name="EditPersonStackPanel" Orientation="Vertical" Background="White" HorizontalAlignment="Center" VerticalAlignment="Center" Width="650" >
<ContentControl>
<StackPanel x:Name="EmailEditStackPanel" Orientation="Horizontal">
<TextBlock Text="Email Address:" Width="200" Margin="5,0,5,0" />
<TextBox x:Name="EmailPopupTextBox" Width="200" />
</StackPanel>
</ContentControl>
<ContentControl>
<StackPanel x:Name="AppliesToDropdownStackPanel" Orientation="Horizontal" Margin="2,2,2,0">
<TextBlock Text="Don't send when update was done by:" />
<StackPanel Orientation="Vertical" MaxHeight="275" MaxWidth="350" >
<TextBlock x:Name="SelectedItemTextBlock" TextAlignment="Right" Width="200" Margin="5,0,5,0" />
<Grid x:Name="UserDropDownGrid" MaxHeight="75" MaxWidth="200" Visibility="Collapsed" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Hidden" >
<Rectangle Fill="White" />
<Border Background="White">
<ListBox x:Name="UsersListBox" SelectionChanged="UsersListBox_SelectionChanged" ItemsSource="{Binding UserID}" />
</Border>
</Grid>
</StackPanel>
<Button x:Name="DropDownButton" Click="DropDownButton_Click" VerticalAlignment="Top" Width="25" Height="25">
<Path Height="10" Width="10" Fill="#FF000000" Stretch="Fill" Stroke="#FF000000" Data="M514.66669,354 L542.16669,354 L527.74988,368.41684 z" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="1,1,1,1"/>
</Button>
</StackPanel>
</ContentControl>
<TextBlock Text="Where Clause Condition:" />
<TextBox x:Name="WhereClauseTextBox" Height="200" Width="800" AcceptsReturn="True" TextWrapping="Wrap" />
<ContentControl>
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<Button x:Name="TestConditionButton" Content="Test Condition" Margin="5,5,5,5" Click="TestConditionButton_Click" />
<Button x:Name="Save" Content="Save" HorizontalAlignment="Right" Margin="5,5,5,5" Click="Save_Click" />
<Button x:Name="Cancel" Content="Cancel" HorizontalAlignment="Right" Margin="5,5,5,5" Click="Cancel_Click" />
</StackPanel>
<TextBlock x:Name="TestContitionResults" Visibility="Collapsed" />
</StackPanel>
</ContentControl>
</StackPanel>
</Border>
</Grid>
</Grid>
And the call that occurs when the grid's selection is changed:
Private Sub IncidentGrid_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
If mFirstTime Then
mFirstTime = False
Else
Dim data As SimpleASMX.EMailMonitor = CType(IncidentGrid.SelectedItem, SimpleASMX.EMailMonitor)
Dim selectedGridItem As SimpleASMX.EMailMonitor = Nothing
If IncidentGrid.SelectedItem IsNot Nothing Then
selectedGridItem = CType(IncidentGrid.SelectedItem, SimpleASMX.EMailMonitor)
EmailPopupTextBox.Text = selectedGridItem.Address
SelectedItemTextBlock.Text = selectedGridItem.AppliesToUserID
WhereClauseTextBox.Text = selectedGridItem.whereClause
IncidentGrid.SelectedIndex = mEmailMonitorData.IndexOf(selectedGridItem)
End If
If IncidentGrid.SelectedIndex > -1 Then
EditPersonPopupGrid.Visibility = Windows.Visibility.Visible
Else
EditPersonPopupGrid.Visibility = Windows.Visibility.Collapsed
End If
End If
End Sub
Sorry if my code is atrocious, I'm still learning Silverlight.
That looks like a Silverlight bug to me. I've just tried it and what's happening on my end is that the SelectionChanged event fires twice when you click the column header and to make matters worse, the index of the selected item doesn't stay synched with the currently selected item.
I'd suggest you work your way around it by using the knowledge that the first time SelectionChanged fires, the value of the datagrid's SelectedItem property will be null
Here's some sample code that at least lives with the issue. Your SelectionChanged logic can go in the if clause.
public partial class Page : UserControl
{
private Person _currentSelectedPerson;
public Page()
{
InitializeComponent();
List<Person> persons = new List<Person>();
persons.Add(new Person() { Age = 5, Name = "Tom" });
persons.Add(new Person() { Age = 3, Name = "Lisa" });
persons.Add(new Person() { Age = 4, Name = "Sam" });
dg.ItemsSource = persons;
}
private void SelectionChanged(object sender, EventArgs e)
{
DataGrid grid = sender as DataGrid;
if (grid.SelectedItem != null)
{
_currentSelectedPerson = grid.SelectedItem as Person;
}
else
{
grid.SelectedItem = _currentSelectedPerson;
}
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Frozen Columns in Silverlight DataGrid..
http://dotnetdreamer.wordpress.com/2009/01/31/silverlight-2-datagrid-frozen-columns/
There's a bugfix for the first issue you mentioned (selection changed event getting fired on resort).
See the following URL for Microsoft's patch:
http://www.microsoft.com/downloads/details.aspx?familyid=084A1BB2-0078-4009-94EE-E659C6409DB0&displaylang=en
This worked, but now if I sort twice, on the first one it sorts, and then does the popup as the first selected item of the grid . If I close the popup grid, and then try to sort a second time, it stack overflows, and crashes firefox out.
I'm thinking I may need to rethink working in silverlight until the system gets a bit more stable.
Thanks for the answer Hovito!