How to change Flipviewitem from Flipview dynamically using c# - windows-phone-8.1

I am working on Windows phone 8.1 winRT App and try to load FilpviewItem from code behind using the index property but its not working for me how we slide flipviewitem from c#
Following is my code which is not working
<FlipView x:Name="flip" Grid.Row="1" Grid.ColumnSpan="4" Grid.Column="0" Margin="0,0,0,0.333" Grid.RowSpan="2">
<FlipViewItem>
<Button Foreground="White" Background="Black" x:Name="btnAdd" Content="Add" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Center" Tapped="btnAdd_Tapped" ></Button>
</FlipViewItem>
<FlipViewItem>
<Button x:Name="btny2" Content="mov" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Center" Tapped="btny2_Tapped" ></Button>
</FlipViewItem>
<FlipViewItem>
<Button x:Name="btnUpdate" Content="Upd" Grid.Row="1" Grid.Column="2" HorizontalAlignment="Right" Tapped="btnupdate_Tapped" ></Button>
</FlipViewItem>
<FlipViewItem>
<Button x:Name="btnRemove" Content="Rem" Grid.Row="1" Grid.Column="3" HorizontalAlignment="Center" Tapped="btnRemove_Tapped" ></Button>
</FlipViewItem>
</FlipView>
private void btnAdd_Tapped(object sender, TappedRoutedEventArgs e)
{
flip.SelectedIndex++;
}
private void btnupdate_Tapped(object sender, TappedRoutedEventArgs e)
{
flip.SelectedIndex++;
}
private void btny2_Tapped(object sender, TappedRoutedEventArgs e)
{
flip.SelectedIndex++;
}
private void btnRemove_Tapped(object sender, TappedRoutedEventArgs e)
{
flip.SelectedIndex++;
}

The amusing thing here is that your code works perfectly well when I copy paste it on my system. However, you could use data binding to achieve this in a cleaner manner.
How To do it with data binding:
create a property named FlipSelectedIndex for example.
private int flipSelectedIndex = 0;
public int FlipSelectedIndex
{
get { return flipSelectedIndex; }
set
{
if (value <= flip.Items.Count - 1)
{
flipSelectedIndex = value;
RaisePropertyChanged("FlipSelectedIndex");
}
}
}
Add an INotifyPropertyChangedinterface and implement it implicitly and then add an event to it called RaisePropertyChanged do this by adding a ,INotifyPropertyChangedinterface to ClassName : Page declaration and add the following method:
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string property)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
Please Note: The PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); Only works with C# 6.0 which is available in Visual Studio 2015. For any editions you will have to use
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
Once done now it's simple: at a button tap simply use FlipSelectedIndex++; or FlipSelectedIndex--; as required.
Update the XAML with adding the SelectedIndex property of the Flipview to data binding like this: SelectedIndex="{Binding FlipSelectedIndex,Mode=TwoWay}" Use two way binding to ensure your FlipSelectedIndex also updates if you change the selected view on the Flipview from the swipe action instead of the button.
Please do remember to add that data context of the page to the code behind using DataContext="{Binding RelativeSource={RelativeSource Self}}" Else the binding won't work.
For more information you could refer to my answer on the FlipView here

Related

Bindings not set for items not visible

Sorry if this is a dumb question. I am maintaining this crazy Windows Phone 8.1 RT dynamic app that I didn't write. It loads up a whole bunch of stuff to the DataContext. Things that aren't visible on the screen don't seem to get their DataContext. When I navigate away from the form the event fires. What do I need to do to fix that? Even when it scrolls into view it doesn't load. If I scoll up and click the back button I see the field populate before it goes to the previous page.
Edit - Here is some code:
<DataTemplate x:Key="com.somecompany.BarcodeboxRenderer">
<Grid HorizontalAlignment="Stretch" DataContext="{Binding Item1}">
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Label}" HorizontalAlignment="Stretch" Style="{StaticResource labelstyle}" Grid.Row="0" />
<somecompany:BarcodeBox IsReadOnly="{Binding DisplayOnly}" somecompany:DynamicDataBindingPath.BindingPath="{Binding FieldId}" Grid.Row="1" />
</Grid>
</DataTemplate>
That calls this but only if it's visible:
public sealed class DynamicDataBindingPath:FrameworkElement
{
public static readonly DependencyProperty BindingPathProperty = DependencyProperty.RegisterAttached("BindingPath", typeof(string), typeof(DynamicDataBindingPath), new PropertyMetadata("", OnBindingPathPropertyChanged));
public static string GetBindingPath(FrameworkElement target)
{
try
{
return (string)target.GetValue(BindingPathProperty);
}
catch (Exception)
{
return string.Empty;
}
}
public static void SetBindingPath(FrameworkElement target, string value)
{
target.SetValue(BindingPathProperty, value);
target.Loaded += Target_Loaded;
}
private static void Target_Loaded(object sender, RoutedEventArgs e) {
var target = (FrameworkElement)sender;
if (target is ...) { ... }
else if (target is DatePicker)
{
int startingletterindex = value.IndexOf('.') + 1;
string pathtobindto = "obj." + Char.ToUpper(value[startingletterindex]) + value.Substring((startingletterindex + 1));
Binding newbind = new Binding();
newbind.Path = new PropertyPath(pathtobindto);
var contextsrc = findRealDataContext(target);
newbind.Source = contextsrc.DataContext;
newbind.Mode = BindingMode.TwoWay;
(target as DatePicker).SetBinding(DatePicker.DateProperty, newbind);
}
else if (...)
}
I turned of ListView Virtualization and it works now. I don't need it because there will never be more than a handful of rows.

How to popup ContextMenu in ListBox programmatically on Windows Phone?

I have a ListBox in my page, I want some items in the ListBox can popup ContextMenu when you long press it, and some items don't, how can I implement this requriment programmatically?
Here is one possible solution. Define your Item's class with some information about popup:
public class Item
{
public string Info { get; set; }
// Menu attached or not
public bool OptionsEnabled { get; set; }
}
In XAML you will have to define your ListView (or ListBox) with apropriate ItemTelplate:
<ListView Name="myList" Holding="myList_Holding">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Info}" FontSize="24" Margin="7">
<FlyoutBase.AttachedFlyout>
<MenuFlyout>
<MenuFlyoutItem Text="First option"/>
<MenuFlyoutItem Text="Second option"/>
</MenuFlyout>
</FlyoutBase.AttachedFlyout>
</TextBlock>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Then upon Holding event you can check OptionsEnabled property if to show a menu,if yes then do so:
private void myList_Holding(object sender, HoldingRoutedEventArgs e)
{
if (e.OriginalSource == null || !(e.OriginalSource is TextBlock)) return;
TextBlock listItem = e.OriginalSource as TextBlock;
if (listItem.DataContext == null) return;
Item itemData = listItem.DataContext as Item;
if (itemData.OptionsEnabled)
FlyoutBase.ShowAttachedFlyout(listItem);
}
A working sample you can download here.

Convertion of long in Windows store application

I am writing a windows 8 store application and have the following problem:
I have a textblock binded to a long property of an object.
The long value is 123456789, however, on the screen i only see the char 1.
How can i solve this, and why the convertion to string doesn't work like it should?
Try this and let me if it works for you or not.
XAML
<Page.DataContext>
<local:myVm />
</Page.DataContext>
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<GridView ItemsSource="{Binding col}">
<GridView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" Margin="20" FontSize="20" />
</DataTemplate>
</GridView.ItemTemplate>
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<WrapGrid MaximumRowsOrColumns="3" />
</ItemsPanelTemplate>
</GridView.ItemsPanel>
</GridView>
</Grid>
myVm.cs
public class myVm : INotifyPropertyChanged
{
public myVm()
{
col.Add(long.MaxValue);
col.Add(long.MaxValue);
col.Add(long.MaxValue);
col.Add(long.MaxValue);
col.Add(long.MaxValue);
col.Add(long.MaxValue);
}
private ObservableCollection<long> _col = new ObservableCollection<long>();
public ObservableCollection<long> col
{
get { return _col; }
set
{
_col = value;
NotifyPropertyChanged("col");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
}

Viewing the top items in a LongListSelector on WP8 when SIP is open

I have an app that uses a LongListSelector to display a list of items, at the bottom of the page I have a TextBox. When the TextBox is tapped, the SIP displays itself. At this point, I'm unable to then scroll to the top of the LLS.
Sample code:
XAML:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<phone:LongListSelector x:Name="TheList">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"
Style="{StaticResource PhoneTextLargeStyle}"/>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</Grid>
<Grid Grid.Row="1">
<TextBox />
</Grid>
</Grid>
C#:
public MainPage()
{
InitializeComponent();
Loaded += (sender, args) =>
{
var list = new List<string>();
for (var i = 0; i < 30; i++)
{
list.Add("This is string number " + i);
}
TheList.ItemsSource = list;
};
}
This is as much as I can see, I can pull down to string number 5, but can't see any higher:
Anyone got any ideas?
The ScrollViewer doesn't take into account the SIP so its scrolling experience is the same as when the SIP is not visible (which is why the top can't be reached). One workaround would be to add a margin to the top of the LongListSelector, (or the bottom if your textbox is at the top), when the SIP is displayed.
As there's no event for the SIP, you can handle the GotFocus and LostFocus events of the TextBox. (The 180 value was obtained via trial and error)
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
TheList.Margin = new Thickness(0,180,0,0);
}
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
TheList.Margin = new Thickness();
}

Why there is no PlaceHolder like property in XAML TextBox

Is there any "placeholder type" property availble for textbox in xaml in windows phone 8
There is the PhoneTextBox in the official Windows Phone Toolkit, covered here.
Sample code:
<toolkit:PhoneTextBox Hint="Password"/>
To add toolkit to your project :
Type the following into your package manager console :
PM> Install-Package WPtoolkit
And
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
inside <phone:PhoneApplicationPage tag in the xaml page
Try like this below code:
<TextBox x:Name="InvoiceDate" Text="" Width="300" TextAlignment="Left" Height="30" Grid.Row="0" Grid.Column="3" Grid.ColumnSpan="2" />
<TextBlock IsHitTestVisible="False" Text="Men att läsa" Width="300" TextAlignment="Left" Height="30" Grid.Row="0" Grid.Column="3" Grid.ColumnSpan="2" Padding="5, 5, 5, 5" Foreground="LightGray">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Text, ElementName=InvoiceDate}" Value="">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
There is no placeholder property for TextBox. I use the following solution to work around this for a username textbox:
XAML:
<Grid>
<TextBlock Name="UsernamePlaceholder" Text="Username" />
<TextBox Name="UsernameTextBox" Text="" GotFocus="TextBox_GotFocus" LostFocus="TextBox_LostFocus"/>
</Grid>
Code:
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
UsernamePlaceholder.Visibility = Visibility.Collapsed;
}
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
if (sender is TextBox)
{
var textbox = sender as TextBox;
if (string.IsNullOrEmpty(textbox.Text))
{
UsernamePlaceholder.Visibility = Visibility.Visible;
}
}
}
This basically replaces the TextBox with a Grid-element, containing a TextBox and a TextBlock (working as placeholder). Then when the textbox is focused, the textblock is hidden, and when it looses focus the textblock is shown if the textbox is empty.
My solution is based on the answer of PKENO
XAML (UserControl):
<UserControl x:Class="FestivalProject.Controls.TextBoxPH"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d">
<TextBox x:Name="testTextBox" Margin="0" LostFocus="testTextBox_LostFocus" GotFocus="testTextBox_GotFocus"/>
</UserControl>
Code behind UserControl:
public partial class TextBoxPH : UserControl
{
private String _Text;
public String Text
{
get { return _Text; }
set {
_Text = testTextBox.Text = value;
}
}
private String _PlaceHolder;
public String PlaceHolder
{
get { return _PlaceHolder; }
set {
_PlaceHolder =testTextBox.Text = value;
}
}
public TextBoxPH()
{
InitializeComponent();
}
private void testTextBox_LostFocus(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(testTextBox.Text)) testTextBox.Text = PlaceHolder;
}
private void testTextBox_GotFocus(object sender, RoutedEventArgs e)
{
if (testTextBox.Text.Equals(PlaceHolder, StringComparison.OrdinalIgnoreCase)) testTextBox.Text = string.Empty;
}
}
XAML (in Window):
<txtPH:TextBoxPH Margin="5" Grid.ColumnSpan="2" PlaceHolder="PlaceholderText"/>
Probably not the most efficient way, but it works.