MasterDetailView UWP - Access the ListView (or make it scroll) - xaml

I recently discovered the UWP Community Toolkit and I loved it. I'm using now the MasterDetailView and it's almost perfect for what I need: but it's missing one important thing: I cannot access the internal "ListView".
In my application I have two buttons: forward and back, and when pressing them I simply go forward and back in the list. I found a trick to access the prev/next element doing like this:
public void GoForward()
{
if (MasterDetailView.Items.Count > 0)
{
bool isNextGood = false;
MyItem selectedItem = MasterDetailView.Items[MasterDetailView.Items.Count - 1] as MyItem;
foreach (var v in MasterDetailView.Items)
{
if (isNextGood)
{
selectedItem = v as MyItem;
break;
}
if (v == MasterDetailView.SelectedItem)
isNextGood = true;
}
MasterDetailView.SelectedItem = selectedItem;
}
}
This just because I cannot access the "SelectedIndex" and I have only SelectedItem avaiable. Now, obviously not all the item can be visible at the same time, so MasterDetailView provide a lateral ListView with a scrollbar. When pressing my next/prev buttons SelectedItem changes, but doesn't scroll at the selected element: selection goes forward/back but the list is locked. This produce a very negative feedback because I lost my selection somewhere in the list and I must search it.
How I though to solve it? I try this approaches:
1) Find the style for MasterDetailView. Inside I found a ListViewStyle, so I tried to put inside a simple "SelectionChanged" event and handle it at App.xaml.cs.
<ListView x:Name="MasterList"
Grid.Row="1"
IsTabStop="False"
ItemContainerStyle="{TemplateBinding ItemContainerStyle}"
ItemTemplate="{TemplateBinding ItemTemplate}"
ItemTemplateSelector="{TemplateBinding ItemTemplateSelector}"
ItemsSource="{TemplateBinding ItemsSource}"
SelectedItem="{Binding SelectedItem, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
SelectionChanged="MasterList_SelectionChanged"/>
CS:
private void MasterList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListView list = sender as ListView;
list.ScrollIntoView(list.SelectedItem);
}
But, as said, "Events cannot be set in the Application class XAML file".
2) Think about taking the parent of SelectedItem: I tried to convert the SelectedItem in ListViewItem, then access the parent, but it fails at first conversion, as the SelectedItem seems no to be a ListViewItem, but it's of the "MyItem" type. Like this, I cannot access the parent.
private void MasterDetailView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var item = MasterDetailView.SelectedItem as ListViewItem;
var parent = item.Parent;
var list = parent as ListView;
}
And so I'm here... I don't want to throw away all my work with the MasterDetailView to pass to another control. Is there any simple method to access the list, or simply, scroll the list when I'm changing selection? Just wanna to do one thing, like this:
private void List_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListView list = sender as ListView;
list.ScrollIntoView(list.SelectedItem);
}
Simply scrolling into selection when selection changed occurred, but I have no simple ListView but a MasterDetailView control. Even if it's done entirely in XAML: the most important thing for me is make scroll this list!
Thanks.
 
 
Solution
This method is fantastic. Just copy-paste.
public static T FindChildOfType<T>(DependencyObject root) where T : class
{
var queue = new Queue<DependencyObject>();
queue.Enqueue(root);
while (queue.Count > 0)
{
DependencyObject current = queue.Dequeue();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(current); i++)
{
var child = VisualTreeHelper.GetChild(current, i);
var typedChild = child as T;
if (typedChild != null)
{
return typedChild;
}
queue.Enqueue(child);
}
}
return null;
}
Then simply use it to retrive the list and make it scroll. Yes babe!
private void MasterDetailView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var v = FindChildOfType<ListView>(MasterDetailView);
v.ScrollIntoView(MasterDetailView.SelectedItem);
}
Please note that "MasterDerailView" Is the x:Name of my element, not the class.

You can use a FindChildOfType implementation to get the ListView through VisualTreeHelper, as indicated in this answer:
Windows UWP - How to programmatically scroll ListView in ContentTemplate

Related

How to set focus to an element inside of user control on UWP?

I created my own UserControl, inside of it, I placed a ListView. But When I set the UserControl to show, I can't set focus to ListViewItem. The Focus is still in the original page.
For how to show my UserControl, I use Popup.
Popup popup = new Popup();
popup.Child = this;
popup.IsOpen = true;
Setting a Focus for a ListView takes place when the ListView has been loaded into the visual tree and ready for interaction.
We assume that you have created a UserControl that contains a ListView, then the method for setting the Focus for the ListView should be done in the UserControl_Loaded or ListView_Loaded event.
public PopupControl()
{
this.InitializeComponent();
// Data init
var _popup = new Popup();
_popup.Child = this;
_popup.IsOpen = true;
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
TestListView.Focus(FocusState.Keyboard);
}
Best regards.

Value of property binded to a TextBlock inside a User Control is not being detected

I've created a UserControl, LiveTile.xaml (streamlined for brevity):
<UserControl
x:Class="Weathercast.Core.LiveTile"
xmlns:local="clr-namespace:Weathercast.Core">
<StackPanel
x:Name="LayoutRoot">
<StackPanel
x:Name="TileRegularFront"
Width="336"
Height="336"
Background="Red">
<TextBlock Text="{Binding TempCurrentHour}"/>
</StackPanel>
</UserControl>
Its code behind, LiveTile.xaml.cs:
public partial class LiveTile : UserControl
{
public LiveTile()
{
InitializeComponent();
LiveTileViewModel vm = new LiveTileViewModel();
this.DataContext = vm;
}
}
Its view model, LiveTileViewModel.cs:
public class LiveTileViewModel : ObservableObject
{
/** PROPERTIES **/
private string _tempCurrentHour;
public string TempCurrentHour
{
get { return _tempCurrentHour; }
set
{
_tempCurrentHour = value;
RaisePropertyChanged("TempCurrentHour");
}
}
/** CONSTRUCTOR **/
public LiveTileViewModel()
{
this.TempCurrentHour = "15"; // dummy value set
}
}
ObservableObject.cs:
public abstract class ObservableObject : INotifyPropertyChanged, INotifyPropertyChanging
{
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
The problem is the value I'm binding ("TempCurrentHour") is not being displayed. Any ideas on what I need to do in order to get the User Control's View Model's binded property value to display? Based on my research, I believe binding a value to a User Control is less straightforward than normal. However I can't get my head around what needs to be done to get the User Control to detect binded property values.
UPDATE: Just to be clear, the LiveTile class is in a Library project for my solution. An instance of it is created when the user toggles on the Live Tile via the Settings PhoneApplicationPage located in the Windows Phone App project in the solution. This is the event handler that instantiates a LiveTile in Settings.xaml.cs:
private void LiveTile_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Weathercast.Core.LiveTile l = new Weathercast.Core.LiveTile();
l.CreateOrUpdateTile(1);
}
The CreateOrUpdateTile method is doing its job correctly and takes the user back to their phone's Start screen with the Live Tile now there. This is its code in any case (I'm using Telerik's LiveTileHelper):
RadFlipTileData tileData = new RadFlipTileData()
{
VisualElement = this.TileRegularFront,
BackVisualElement = this.TileRegularBack,
SmallVisualElement = this.TileSmall
};
// Tile's uri has a unique paramater which is the location Id of the currently viewed location.
Uri tileUri = new Uri("/MainPage.xaml?locationId=" + locationId, UriKind.RelativeOrAbsolute);
// If the tile for this location previously existed, delete it before adding it anew.
ShellTile tile = LiveTileHelper.GetTile(tileUri);
if (tile != null)
{
tile.Delete();
}
// Create brand new tile for location if didn't have tile previously or fresh tile if it did.
LiveTileHelper.CreateOrUpdateTile(tileData, tileUri, true);
this.tile = tileData;
// Add the Background Agent for this tile with the agent's name
// unique for the location.
AddAgent("PeriodicTaskForLocation" + locationId);
I should note another problem I'm having, that may or may not be related to the original issue, is that the background property I'm setting in LiveTile.xaml for the StackPanel or LayoutRoot element even is being neglected and the Live Tile that's being added to the Start screen is transparent (black).

Child controls grow unlimited in custom XAML control. What's wrong?

I've implemented a Windows 8 XAML VisibilitySwitchControl that displays the first child on certain condition; otherwise the other controls are shown. The code is as follows
[ContentProperty(Name = "Items")]
public class VisibilitySwitchControl : ItemsControl
{
public VisibilitySwitchControl()
{
DefaultStyleKey = typeof(VisibilitySwitchControl);
if (Items != null)
Items.VectorChanged += OnItemsChanged;
}
public bool ShowFirst
{
get { return (bool)GetValue(ShowFirstProperty); }
set { SetValue(ShowFirstProperty, value); }
}
public static readonly DependencyProperty ShowFirstProperty =
DependencyProperty.Register("ShowFirst", typeof(bool), typeof(VisibilitySwitchControl), new PropertyMetadata(true, OnShowFirstChanged));
public object VisibleContent
{
get { return GetValue(VisibleContentProperty); }
private set { SetValue(VisibleContentProperty, value); }
}
public static readonly DependencyProperty VisibleContentProperty =
DependencyProperty.Register("VisibleContent", typeof(object), typeof(VisibilitySwitchControl), new PropertyMetadata(null));
private static void OnShowFirstChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
var visibilityItemsControl = d as VisibilitySwitchControl;
if (visibilityItemsControl != null)
{
visibilityItemsControl.Evaluate();
}
}
void OnItemsChanged(IObservableVector<object> sender, IVectorChangedEventArgs evt)
{
Evaluate();
}
void Evaluate()
{
if (Items != null && Items.Any())
{
var controls = Items.OfType<FrameworkElement>().ToList();
for (var i = 0; i < controls.Count; i++)
{
if (i == 0)
{
VisibleContent = controls[i];
controls[i].Visibility = ShowFirst ? Visibility.Visible : Visibility.Collapsed;
}
else
{
controls[i].Visibility = !ShowFirst ? Visibility.Visible : Visibility.Collapsed;
}
}
}
else
{
VisibleContent = null;
}
}
}
However, if I place two ListView controls inside my VisibilitySwitchControl the ListView can grow in way that it is larger than the page and no scrollbars are shown. It doesn't stop a the parent containers bounds.
<custom:VisibilitySwitchControl ShowFirst="{Binding Path=IsFirstLevelNav}">
<ListView x:Name="FirstListView"
VerticalAlignment="Stretch"
ItemsSource="{Binding ...}"
SelectedItem="{Binding ..., Mode=TwoWay}"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
/>
<ListView x:Name="SecondListView"
VerticalAlignment="Stretch"
ItemsSource="{Binding ...}"
SelectedItem="{Binding ..., Mode=TwoWay}"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
/>
</custom:VisibilitySwitchControl>
How can I enforce a VerticalAlignment="Stretch" behavior of the children? If I remove my control and place only one the lists directly in the code, everything works as expected.
Thanks for suggestions.
you want to stretch the Height of the listview try binding it to the actual height of the parent
Heres the code part you need to include
Height="{Binding ActualHeight, ElementName=parentContainer}"
where parentContainer is the name of the custom:VisibilitySwitchControl you are using . this will bind the height to the parent container's display height. Try and let me know
If what you want is that you scroll one ListView and then when you reach the end it show the second ListView then you just need to add a ScrollViewer around the ItemPresenter inside the style of VisibilitySwitchControl and disable the ListView ScrollViewer. Just note that it mean that you will lost the virtualisation inside the ListView.
If what you want is each ListView taking half the screen than the easiest is probably to just set a Fix height for each items depending on Window.Current.Bounds.Height and register for Window.Current.SizeChanged to update it when the windows heigh changed (make sure to unregister it in unloaded to prevent memory leak).
An alternative which I think would be more complicated, would be to change the ItemsPanel of VisibilitySwitchControl to something else (by default it is a Stack panel so it will grow larger than the screen) like for example to a Grid in which you set as many row with star heigh as items you have (and then you will need to set the row of each item) or by creating a custom Panel.

XAML: Tap a textbox to enable?

In XAML and WinRT, Is there a way to set up a textbox so that it is disabled for text input until it is tapped.
I tried setting up the Tapped event and then setting the IsEnabled=true, but that only seems to work if the IsEnabled=true in the first place.
I found this on MSDN:
http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/708c0949-8b06-40ec-85fd-201139ca8b2d
Talks about adding the TappedEvent manually to the event handled for each TextBox, which is cumbersome, but also doesn't seem to work unless IsEnabled was already set to true.
Basically, I want a form where all textboxes display data but are disabled unless the user taps to enable the box and then type.
You can use IsReadOnly instead of IsEnabled to achieve what you are looking for. In addition, you can set up the tapped event handlers in code easily. I'm not sure if setting up handlers in code is a requirement for this to work, as you noted above; however, it does simplify things.
Here are the details.
In the constructor of your page class (here it is MainPage), call the setup function:
public MainPage()
{
this.InitializeComponent();
// call the setup for the textboxes
SetupTextBoxes();
}
Here is where we do the magic - make all textboxes on this page readonly and set up tap handler:
private void SetupTextBoxes()
{
var tbs = GetVisualChildren<TextBox>(this, true);
foreach (var tb in tbs)
{
tb.IsReadOnly = true;
tb.AddHandler(TappedEvent, new TappedEventHandler(tb_Tapped), true);
}
}
Utility function to get a list of all children of the given type (T) of the passed in parent.
private List<T> GetVisualChildren<T>(DependencyObject parent, bool recurse = true)
where T : DependencyObject
{
var children = new List<T>();
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
DependencyObject v = (DependencyObject)VisualTreeHelper.GetChild(parent, i);
var child = v as T;
if (child == null && recurse)
{
var myChildren = GetVisualChildren<T>(v, recurse);
children.AddRange(myChildren);
}
if (child != null)
children.Add(child);
}
return children;
}
Finally, the event handler. This enables each textbox when tapped.
private void tb_Tapped(object sender, TappedRoutedEventArgs e)
{
((TextBox)(sender)).IsReadOnly = false;
}

Bing maps resizable polygon

I am trying to implement the ability for a user to draw and refine a polygon on a Bing Map control.
I have added a shape layer, and overridden the tap events to draw a simple polygon and that all works perfectly. I would like to further refine the control so that a user can drag and drop any of Location objects of the drawn polygon to alter its shape, but I'm not having any luck.
I have tried to add a MapItemControl, bound to the Locations property of my polygon, but without success - I don't see the pins appear on the map, even though my polygon does render correctly. Presumably the Locations collection isn't notifying the UI of any changes to the collection, so I may have to maintain a separate collection for these pins.
Once I get this going, however, I still need to be able to drag and drop the pins around to modify the polygon. Has anyone implemented this on Windows 8 that could share some thoughts, please?
EDIT
I now have my pins showing the Locations collection on the map. I'd ideally like to tie these back to the Locations collection of the polygon, but beggars can't be choosers. I now just need to be able to drag the pins around.
I added a drag handle module to the polygon in order to edit each point in the polygon. This is the walk-through I used.
Drag Handle Module
This is for version 7.0. Not sure which version you are using, but it is easily adaptable.
Edit I did this in javascript/html. Just noticed you tagged this as windows 8. Curious, are you making a silver-light control for windows 8 phones?
WPF C# Solution
Here is what I came up with and it is very easy to implement, all you need to do is hook my event onto your MapPolygon object. The idea behind the code, is once you click on the polygon, we place a pushpin (which we create events so that we can drag it) at each vertice on the polygon. As we drag and drop each pushpin we adjust the polygon.Locations as applicable.
polygon.MouseDown += new MouseButtonEventHandler(polygon_MouseDownResize);
And a way to exit the resize event, I choose to just hook onto the key down and used 'esc' to stop editing, but you can do this on right click or any other event you choose to. All your doing is clearing pushPinVertices list and resetting event variables.
// === Editable polygon Events ===
private bool _shapeEdit;
public MapPolygon selectedPoly { get; set; }
public List<Pushpin> pushPinVertices { get; set; }
void polygon_MouseDownResize(object sender, MouseButtonEventArgs e)
{
if (!_shapeEdit && selectedPoly == null)
{
_shapeEdit = true;
selectedPoly = sender as MapPolygon;
pushPinVertices = new List<Pushpin>();
int i = 0;
foreach (Microsoft.Maps.MapControl.WPF.Location vertice in selectedPoly.Locations)
{
Pushpin verticeBlock = new Pushpin();
// I use a template to place a 'vertice marker' instead of a pushpin, il provide resource below
verticeBlock.Template = (ControlTemplate)Application.Current.Resources["PushPinTemplate"];
verticeBlock.Content = "vertice";
verticeBlock.Location = vertice;
verticeBlock.MouseDown += new MouseButtonEventHandler(pin_MouseDown);
verticeBlock.MouseUp += new MouseButtonEventHandler(pin_MouseUp);
myMap.Children.Add(verticeBlock);
pushPinVertices.Add(verticeBlock);
i++;
}
}
}
private void myMap_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Escape)
{
if (_shapeEdit && selectedPoly != null)
{
foreach (Pushpin p in pushPinVertices)
{
myMap.Children.Remove(p);
}
_shapeEdit = false;
selectedPoly = null;
}
}
}
// Note: I needed my window to pass bing maps the keydown event
private void Window_KeyDown(object sender, KeyEventArgs e)
{
myMap_KeyDown(sender, e);
}
// === Editable polygon Events ===
// ==== Draggable pushpin events =====
Vector _mouseToMarker;
private bool _IsPinDragging;
public Pushpin SelectedPushpin { get; set; }
void pin_MouseUp(object sender, MouseButtonEventArgs e)
{
LocationCollection locCol = new LocationCollection();
foreach (Pushpin p in pushPinVertices)
{
locCol.Add(p.Location);
}
selectedPoly.Locations = locCol;
bingMapRefresh();
_IsPinDragging = false;
SelectedPushpin = null;
}
void pin_MouseDown(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
SelectedPushpin = (Pushpin)sender;
_IsPinDragging = true;
_mouseToMarker = Point.Subtract(
myMap.LocationToViewportPoint(SelectedPushpin.Location),
e.GetPosition(myMap));
}
private void myMap_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
if (_IsPinDragging && SelectedPushpin != null)
{
SelectedPushpin.Location = myMap.ViewportPointToLocation(Point.Add(e.GetPosition(myMap), _mouseToMarker));
e.Handled = true;
}
}
}
// ==== Draggable pushpin events =====
// Nice little maprefresh I found online since the bingmap WPF doesnt always seem to update elements after certain event orders
private void bingMapRefresh()
{
//myMap.UpdateLayout();
var mapCenter = myMap.Center;
mapCenter.Latitude += 0.00001;
myMap.SetView(mapCenter, myMap.ZoomLevel);
}
As for the resource to overwrite the pushpin icon, I just used an ImageBrush an made a small white square. Note you may need to adjust the Margin property depending on how long / wide you make your marker. This is because generally the pushpin is anchored above the location by default.
<Application.Resources>
<ControlTemplate x:Key="PushPinTemplate">
<Grid>
<Rectangle Width="10" Height="10" Margin="0 35 0 0">
<Rectangle.Fill>
<ImageBrush ImageSource="pack://application:,,,/Images/DragIcon.gif"/>
</Rectangle.Fill>
</Rectangle>
</Grid>
</ControlTemplate>
</Application.Resources>