How can I remove selected row from a grid control - c#

I have created a Grid and adding rows dynamically. And I have a remove button in every row. On click of that remove button I want to remove that particular row.
I am quite new to WPF, can some one help me out to achieve this.
Thanks.
Xaml code:
<Grid Grid.Column="2" Visibility="Collapsed" Name="operationalGrid">
<Button Height="25" Name="btnRemove" Width="24" Style="{DynamicResource ButtonStyle}" Grid.Column="4" Click="btnRemove_Click">
<materialDesign:PackIcon Background="Transparent" Height="25" Width="30" Cursor="Hand" ToolTip="Remove" Kind="Minus" HorizontalAlignment="Center" Foreground="White" VerticalAlignment="Top" Margin="0,0,0,0">
</materialDesign:PackIcon>
</Button>
</Grid>
c# code:
Adding rows:
RowDefinition row = new RowDefinition();
row.Height = GridLength.Auto;
if (ucDynamicControls != null)
ucDynamicControls.btnToggle.Visibility = ucDynamicControls.btnToggle.Visibility = Visibility.Visible;
ucDynamicControls = new ucControls();
grdContols.RowDefinitions.Add(row);
Grid.SetRow(ucDynamicControls, controlCount++);
grdContols.Children.Add(ucDynamicControls);

Instead of using row definitions, you may use ItemsControl.
As example:
First define your ItemTemplate
<ItemsControl Name="icTodoList">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="0,0,0,5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Title}" />
<ProgressBar Grid.Column="1" Minimum="0" Maximum="100" Value="{Binding Completion}" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Define your ItemsPanel
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="3" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
Full tutorial:
https://www.wpf-tutorial.com/list-controls/itemscontrol/

You have come up with a very complex, one might say, perverse way of accomplishing the task.
A typical implementation is to create a container element with data. Then the collection with these elements is passed to ItemsControl. And he already visual each element as it should.
In this implementation: deleting a row is removing an item from the collection.
In your implementation, you need to parse the Visual Element Tree.
It is possible, but difficult.
The button, as I understand it, is inside the Grid row.
This Grid is inside ucDynamicControls.
And the outer Grid row already contains this ucDynamicControls.
If I understood correctly, then in the button event it is necessary to go up from the button to the Grid containing ucDynamicControls.
In this Grid, remove the ucDynamicControls element from the Children collection.
And the line (in which it) is to collapse: Heigh = 0.
And it's not clear why you chose Grid, and StackPanel for the ucDynamicControls collection?
If you use a StackPanel, then it will be possible not to set the line number and for it will be enough just to remove the desired ucDynamicControls from the collection.
An example implementation (if I understand your code correctly):
private void btnRemove_Click(object sender, RoutedEventArgs e)
{
if (!(sender is Button button))
return;
DependencyObject child = button;
DependencyObject parent;
while (!((parent = LogicalTreeHelper.GetParent(child)) is UcDynamicControls) && parent != null)
child = parent;
if (parent == null)
return;
UcDynamicControls ucDynamicControls = (UcDynamicControls)parent;
int row = Grid.GetRow(ucDynamicControls);
Grid grid = LogicalTreeHelper.GetParent(ucDynamicControls) as Grid;
if (grid == null || grid.RowDefinitions.Count <= row)
return;
grid.RowDefinitions[row].Height = new GridLength(0);;
grid.Children.Remove(ucDynamicControls);
}

Related

WPF combination between grid and stackpanel

I am currently trying to find/implement a WPF control, which is a combination of a Grid and a StackPanel. That means, I like to have two columns with several items. An item is another control (e.g. single Label, TextBox with label in a panel, ...).
If an item is collapsed, the empty space should be filled with the next item, means I have always as less space used in the control as possible (without gaps between the single items).
I attached two images how it should look like.
Initial:
Item4 is collapsed (notice the shift of following up items):
Does anybody have an idea or experience how to do something like that?
you can use a ListView that uses a StackPanel or a DockPanel as ItemTemplate.
This is an example (simplified) of what I use to display an observable collection of objects in a list with Grid and DockPannel:
<ListView x:Name="lbxDroppedDatas" SelectionMode="Single" AllowDrop="True" BorderThickness="0" Padding="0" Margin="0" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionChanged="lbxDroppedDatas_SelectionChanged" PreviewKeyDown="lbxDroppedDatas_PreviewKeyDown" PreviewMouseRightButtonDown="lbxDroppedDatas_PreviewMouseRightButtonDown" >
<ListView.ItemTemplate>
<DataTemplate>
<DockPanel Grid.Row="0" Width="{Binding Path=ActualWidth, ElementName=Container}" Height="40" Margin="1" LastChildFill="True">
<CheckBox DockPanel.Dock="Left" IsChecked="{Binding IsChecked}" VerticalAlignment="Center" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked" />
<Label Content="{Binding Name}" Foreground="{Binding LineBrush}" FontWeight="Bold" FontSize="12" Margin="5" HorizontalAlignment="Left" VerticalAlignment="Center" Padding="0" MouseEnter="Label_MouseEnter" MouseLeave="Label_MouseLeave"/>
<TextBox DockPanel.Dock="Right" Width="60" MaxLength="14" Text="{Binding CurrentValue, StringFormat=N}" Margin="0,0,33,0" Background="Transparent" Foreground="{Binding LineBrush}" BorderBrush="{Binding LineBrush}" BorderThickness="1" VerticalAlignment="Center" HorizontalAlignment="Right" IsEnabled="False"/>
</DockPanel>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Vertical" VerticalAlignment="Stretch" Margin="0"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>
You could bind the visibility of your list element to a collapsed or visible property.
I'd solve this problem in the following way:
start with creating a grid with two stack panels (the grid resides within a UserControl or any other placeholder):
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<StackPanel x:Name="LeftPanel" x:FieldModifier="private" Orientation="Vertical" />
<StackPanel x:Name="RightPanel" x:FieldModifier="private" Grid.Column="1" Orientation="Vertical" />
</Grid>
to control your items, create a list of items, preferably within the code of your UserControl:
private List<FrameworkElement> m_items = new List<FrameworkElement>();
for the items you don't want to be visible set the Visibility to Hidden or Collapsed.
you'd need some method that will select the visible items and place them alternating to the left and right panel. I've came up with some quick method that you need to call each time your list changes (an item is added or removed, visibility of an item is changed):
public void SortItems()
{
this.LeftPanel.Children.RemoveRange(0, this.LeftPanel.Children.Count);
this.RightPanel.Children.RemoveRange(0, this.RightPanel.Children.Count);
this.m_items.Where(i => i.Visibility == Visibility.Visible).ToList().ForEach((i) => { (this.LeftPanel.Children.Count == this.RightPanel.Children.Count ? this.LeftPanel : this.RightPanel).Children.Add(i); } );
}
The method simply removes all children of the stack panels and then traverses through the items' list choosing only those which are Visible and adds one to the left panel if both panels have the same amount of items in them and to the right panel otherwise.
If you need some other way of selecting into which panel the following item should be added (e.g. ActualHeight) simply change the condition that is selecting the panels.
If you want to make this method more elegant you can add some events or dependency properties that will call SortItems automatically. Anyway, it's a good start.
Thank you very much for all the different solutions. Finally I solved it with the suggestion from Sinatr. So I created my own panel and override the ArrangeOverride:
protected override Size ArrangeOverride(Size finalSize)
{
List<UIElement> visibleItems = new List<UIElement>();
double xColumn1 = 0;
double xColumn2 = (finalSize.Width / 2) + (WIDTH_COLUMN_SEPERATOR / 2);
double y = 0;
double columnWidth = (finalSize.Width - WIDTH_COLUMN_SEPERATOR) / 2;
for (int i = 0; i < InternalChildren.Count; i++)
{
UIElement child = InternalChildren[i];
if (child.Visibility != Visibility.Collapsed)
{
visibleItems.Add(child);
}
}
for (int i = 0; i < visibleItems.Count; i++)
{
if (i >= (visibleItems.Count - 1))
{
visibleItems[i].Arrange(new Rect(xColumn1, y, columnWidth, visibleItems[i].DesiredSize.Height));
}
else
{
UIElement leftItem = visibleItems[i];
UIElement rightItem = visibleItems[i + 1];
double rowHeight = leftItem.DesiredSize.Height > rightItem.DesiredSize.Height ? leftItem.DesiredSize.Height : rightItem.DesiredSize.Height;
leftItem.Arrange(new Rect(xColumn1, y, columnWidth, rowHeight));
rightItem.Arrange(new Rect(xColumn2, y, columnWidth, rowHeight));
y += rowHeight;
i++;
}
}
return finalSize;
}
I also created my own UserControl for the Items:
<Grid DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label x:Name="captionLabel" Grid.Row="0" Content="{Binding Caption}"/>
<ContentPresenter x:Name="inputMask" Grid.Row="1" Content="{Binding InputMask, ElementName=userControlBRAIN2AttributePanelItem}" />
</Grid>
So I get te following result (from my test application):
enter image description here
with collapsed item 3:
enter image description here
I'm surprised that no one sugested the use of an UniformGrid.
All you have to do is declar an UniformGrid, set Columns to 2 and add your items. Items that are collapsed should have its Visibility set to Collapsed (duh).
Here's an example:
<UniformGrid Columns="2"
VerticalAlignment="Center"
HorizontalAlignment="Center">
<TextBlock Text="Item 1 " />
<TextBlock Text="Item 2 " />
<TextBlock Text="Item 3 " />
<TextBlock Text="Item 4 " />
</UniformGrid>
Will produce the following result:
And when the Visibility of the second TextBlock is set to Collapsed, here's what it looks like:

Is there any control for auto resize items inside

is there any control that can auto resize items inside. I need to contain textblocks inside ItemsControl only in one row, so if total items width larger then container.Width, it will change each item's width. UWP
<ItemsControl Grid.Column="1"
ItemsSource="{Binding Path=NavigationHistory, ElementName=Main, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
x:Name="BroadComb"
MaxHeight="24"
Margin="10,0,0,0" VerticalAlignment="Center" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<HyperlinkButton Command="{Binding Path=NavigateCommand, ElementName=Main}" CommandParameter="{Binding}" Margin="10,0,0,0" Foreground="{ThemeResource AppAccentForegroundLowBrush}" >
<HyperlinkButton.ContentTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock VerticalAlignment="Center"
TextTrimming="None"
Text="{Binding Path=DisplayName}"
FontSize="10"
FontWeight="Bold"
Foreground="{ThemeResource AppAccentForegroundLowBrush}">
<i:Interaction.Behaviors>
<core:DataTriggerBehavior Binding="{Binding Path=CanBeTrim}" Value="True">
<core:ChangePropertyAction PropertyName="TextTrimming" Value="WordEllipsis"/>
</core:DataTriggerBehavior>
<core:DataTriggerBehavior Binding="{Binding Path=CanBeTrim}" Value="False">
<core:ChangePropertyAction PropertyName="TextTrimming" Value="None"/>
</core:DataTriggerBehavior>
</i:Interaction.Behaviors>
</TextBlock>
<FontIcon Margin="10,0,0,0" HorizontalAlignment="Center"
VerticalAlignment="Center"
FontFamily="ms-appx:/Assets/Fonts/MyBook-Regular.ttf#MyBook"
FontSize="10"
Glyph="2" Foreground="{ThemeResource AppAccentForegroundLowBrush}" />
</StackPanel>
</DataTemplate>
</HyperlinkButton.ContentTemplate>
</HyperlinkButton>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
One possibility is to use a Grid with your desired controls in it's columns set to HorizontalAlignment="Stretch":
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="abc" HorizontalAlignment="Stretch" />
<TextBlock Grid.Column="1" Text="xyz" HorizontalAlignment="Stretch" />
</Grid>
This will stretch both controls over the maximum available width according to the Grid's container and make them smaller or bigger if the available space changes.
Most of the time, you will only want to set one column to fill the available space (Width="*") and set the other columns to a fixed or relative width. You can experiment with those settings.
Else we would need a more exact specification of what you want to achieve.
is there any control that can auto resize items inside. I need to contain textblocks inside ItemsControl only in one row, so if total items width larger then container.Width, it will change each item's width. UWP
What you need is to change the default ItemsPanel of GridView. You can create your own Custom Panel to let the texts be arranged in only one row:
Create your own custom Panel OneRowPanel.cs:
public class OneRowPanel:Panel
{
double itemHeight=0;
protected override Size MeasureOverride(Size availableSize)
{
int count = Children.Count;
foreach (FrameworkElement child in Children)
{
child.Measure(new Size(availableSize.Width/count,availableSize.Height));
if (child.DesiredSize.Height > itemHeight)
{
itemHeight = child.DesiredSize.Height;
};
}
// return the size available to the whole panel
return new Size(availableSize.Width, itemHeight);
}
protected override Size ArrangeOverride(Size finalSize)
{
// Get the collection of children
UIElementCollection mychildren = Children;
// Get total number of children
int count = mychildren.Count;
// Arrange children
int i;
for (i = 0; i < count; i++)
{
//get the item Origin Point
Point cellOrigin = new Point(finalSize.Width / count * i,0);
// Arrange child
// Get desired height and width. This will not be larger than 100x100 as set in MeasureOverride.
double dw = mychildren[i].DesiredSize.Width;
double dh = mychildren[i].DesiredSize.Height;
mychildren[i].Arrange(new Rect(cellOrigin.X, cellOrigin.Y, dw, dh));
}
// Return final size of the panel
return new Size(finalSize.Width, itemHeight);
}
}
Use it in your Xaml and set the TextBlock.TextTrimming to CharacterEllipsis:
<Page
x:Class="AutoResizeItemsSample.MainPage"
...
mc:Ignorable="d">
<Page.Resources>
<DataTemplate x:Key="TextTemplate">
<TextBlock Text="{Binding Text}" TextTrimming="CharacterEllipsis">
</TextBlock>
</DataTemplate>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel Name="rootPanel">
<GridView Name="gridView" ItemTemplate="{StaticResource TextTemplate}" >
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<local:OneRowPanel ></local:OneRowPanel>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
</GridView>
</StackPanel>
</Grid>
</Page>
Here is the Result:
Here is the complete demo:AutoResizeItemsSample.
Solve this easily with ListView. The ItemsPanel is already a StackPanel and the individual item will resize as needed. If you need the horizontal width of each item to be different, that's supported out of the box, too. I think the solution is to simply choose the ListView control.

Hide GridViewItem and reposition items in GridView

As you can see above, I need it to reshuffle itself into alignment. Obviously the items still exist, is there a way to completely ignore them?
I have an ObservableCollection:
public static volatile ObservableCollection<MyVideo> MyVideoModels = new ObservableCollection<MyVideo>();
This gets filled with the MyVideo objects.
Binding it to my GridView like so:
public VideosFoundView()
{
this.InitializeComponent();
this.AddVideoFolderGridView.ItemsSource = VideosFoundView.MyVideoModels;
}
The DataTemplate I am using for the GridView.
<GridView Grid.Row="2" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" x:Name="AddVideoFolderGridView">
<GridView.ItemTemplate>
<DataTemplate>
<Border BorderThickness="5">
<Image Source="{Binding FullImageLocationOnDisk}" MaxHeight="300" MaxWidth="200" DoubleTapped="gridViewItem_DoubleTapped" Loaded="gridViewItem_Loaded" Loading="gridViewItem_Loading">
</Image>
</Border>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
And I have a static ToggleSwitch above this GridView like so:
<Grid Grid.Row="1">
<Grid>
<TextBlock Text="Ingore Image Not Found"/>
<ToggleSwitch x:Name="ToggleSwitchIgnoreImages" Toggled="ignoreImages_Toggled"/>
</Grid>
</Grid>
Which does:
private void ignoreImages_Toggled(object sender, RoutedEventArgs e)
{
ToggleSwitch tSwitch = (ToggleSwitch)(sender as ToggleSwitch);
if (tSwitch.IsOn)
{
for(int i = 0; i < VideosFoundView.MyVideoModels.Count; i++)
{
if(VideosFoundView.MyVideoModels[i].FullImageLocationOnDisk == "ms-appx:///Assets/image-not-found.gif")
{
var gridViewItem = (GridViewItem)this.AddVideoFolderGridView.ContainerFromIndex(i);
gridViewItem.Visibility = Visibility.Collapsed;
}
}
}
else
{
for (int i = 0; i < VideosFoundView.MyVideoModels.Count; i++)
{
//VideosFoundView.MyVideoModels[i].Visibility = "Auto";
var gridViewItem = (GridViewItem)this.AddVideoFolderGridView.ContainerFromIndex(i);
gridViewItem.Visibility = Visibility.Visible;
}
}
}
However the problem is that the items are still taking up space on my GridView, and the other items do not re-position themselves accordingly.
The items are still taking up space on the GridView, when the GridViewItem is collapsed. It might because the ItemTemplate has not be refreshed, the space is still reserved.
As a workaround, there is a port of the Toolkit's WrapPanel for UWP in the project WinRTXamlToolkit.
You can get it from NuGet.
Then in your Page add this prefix:
xmlns:toolkit="using:WinRTXamlToolkit.Controls"
Now you can use <toolkit:WrapPanel Orientation="Horizontal" ></toolkit:WrapPanel> as it was before.
For example:
<GridView x:Name="AddVideoFolderGridView">
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel Orientation="Horizontal" >
</toolkit:WrapPanel>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.ItemTemplate>
<DataTemplate>
<Border BorderThickness="5">
<Image Source="{Binding FullImageLocationOnDisk}" MaxHeight="300" MaxWidth="200" DoubleTapped="gridViewItem_DoubleTapped" Loaded="gridViewItem_Loaded" Loading="gridViewItem_Loading">
</Image>
</Border>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
Solution from here: Not showing items with Visibility=Collapsed in Windows 8.1 GridView
tldr:
Edit the template of your GridView and replace the ItemsWrapGrid in the ItemsPanelTemplate with the WrapPanel you can find here http://codepaste.net/8gr5go

Unable to find controls inside DataTemplate in SilverLight5

I am using DataTemplate where I've declared two Buttons and they are invisible by default. Now I want to make them Visible in code behind based on some condition but I am unable to find these controls.
Following is my code:
XAML:
<ItemsControl x:Name="SynonymsItemsControl" ItemsSource="{Binding Synonyms}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" Margin="0,5,0,0" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel x:Name="SynonymsStackPanel">
<CheckBox x:Name="SynonymsChkBx" Content="{Binding Display}" Margin="10,0,0,0" />
WANT TO FIND THESE TWO BUTTONS
<Button x:Name="AddSynonymsBtn" Margin="525, 0, 0, 0" ToolTipService.ToolTip="Add Synonyms" Visibility="Collapsed">
<Image Source="/Images/AddSynonyms.png" Height="24"/>
</Button>
<Button x:Name="CancelSynonymsBtn" Margin="600, 0, 0, 0" ToolTipService.ToolTip="Cancel Synonyms" Visibility="Collapsed">
<Image Source="/Images/CancelSynonyms.png" Height="24"/>
</Button>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
CODE-BEHIND:
I'm able to find ItemControl by doing this,
System.Windows.Controls.ItemsControl itemControl = (from sp in selectedTreeViewItem.GetVisualDescendants().OfType<System.Windows.Controls.ItemsControl>()
where sp.Name == "SynonymsItemsControl"
select sp).FirstOrDefault();
Now When I want to find buttons which are declared inside this ItemsControl->DataTemplate, it comes as Null
Button AddSynonymsBtn = (from btn in itemControl.GetVisualDescendants().OfType<Button>()
where btn.Name == "AddSynonymsBtn"
select btn).FirstOrDefault();
So I am wondering that do I need to find ItemsControl at all? if so, then why am I unable to find these buttons?
I've also tried
var findControl = temControl.ItemContainerGenerator.ContainerFromIndex(index); but same result(Null).
You can easly get controls from behind by using Template.FindName(string Name);
private Button _partSynonyms = null;
public MyControlTemplate{
Loaded += (sender, e) => OnLoaded();
}
private void OnLoaded(){
_partSynonyms = (Button)Template.FindName("PART_AddSynonymsBtn"); //You "should" use PART_ as a prefix in a Template
if(_partSynonyms == null)
//Button not found -> Log some error but you should not throw an exception
}

how to get listbox selected items tag in mainpage xaml

I am developing windows phone 8 app.I need a user response in some part of my application
i create windows phone user control page .User will select a value from a listbox that is in usercontrol page
here is code of my user control page
<Grid x:Name="columngrid" Background="#FF1FCB4E" Width="480" >
<Grid.RowDefinitions>
<RowDefinition Height="300"/>
<RowDefinition Height="70"/>
<RowDefinition Height="70"/>
</Grid.RowDefinitions>
<ListBox Name="URLListBox" Grid.Row="0" Background="#FF1FCB4E" >
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="#FF0B232F" BorderThickness="2">
<TextBlock x:Name="surename" Width="460" Tag="{Binding b1Tag}" Height="80" FontSize="25" Text="{Binding text}" Foreground="#FFBF9595" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10,0" />
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Grid.Row="1" x:Name="btnOK" Content="OK" Background="#FF892121" />
<Button Grid.Row="2" x:Name="btnCancel" Content="Cancel" Background="#FF892121"/>
</Grid>
i want to get selected textblock's text in mainpage.xaml.But When i create class object for user control page i cant reach textblock.I can only reach listbox.How can i get selected textblock's text
I try this but i realized that s will bring listbox object
surah popupsurah = new surah();//usercontrol page
Popup popup2 = new Popup();
private void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
collapsedgrid.Visibility = Visibility.Collapsed;
popupsurah.URLListBox.Tap += (s, args) =>
{
string transferID = ((TextBlock)s).Text as string;
Best way is to do binding with the ListBox SelectedItem property and so you can easily retrieve it from the object itself.
Something like below,(Algorithm)
You can have a class:
class MyClass
{
List<string> Items{get;set;}
string SelectedItem{get;set;}
}
You can pass an instance of this class to the UserControl:
MyUserControl(MyClass);
In the Constructor of MyUserControl:
set the DataContext: this.DataContext=MyClass;
Bind the Property Names in the xaml. Thats it.
Another approach is:
Save the selected Item string into the state dictionary:
PhoneApplicationService.Current.State["SelectedItem"]=YourSelectedItemString;
You can retrieve in the MainPage.xaml like this:
var selectedItem=PhoneApplicationService.Current.State["SelectedItem"] as string;
Better you can go for Phone:LongListSelector control which is more optimised than ListBox,Which has almost all events and properties of ListBox.

Categories