Introduction:
Sometimes we may need to detect hyperlinks from given message.For example I have a Listbox which is binding with multiple message items,but here problem is when user sent hyperlinks to listboxitem message ,then we need to detect hyperlinks from message content and provide action for hyperlink to navigate to linked page.So this post is explained about "How to work with ListboxItems having hyperlinks?". At present this post may not be useful for you,but i am sure it will definitely helpful for you in future :)Requirements:
This sample is targeted to windowsphone 7.1 OS.
Description:
To detect hyperlinks from listboxitem in app we need to follow the certain steps given below.
Step 1:
In DataTemplate of Listbox,I taken WrapPanel which is great for laying out things in a vertical or horizontal orientation until you reach the edge of the container and then moving on to the next column or row.In xaml code i added Loaded event for wrappanel ,so that in Loaded event fire i can detect hyperlinks from bindable message content as well as i can set action for hyperlinks by adding HyperlinkButton to wrappanel.
To use WrapPanel ,we need add Microsoft.Phone.Controls.Toolkit.dll references . And make sure the DLL is added to the references as in the following:
Open MainPage.xaml and add the toolkit namespace in xaml:
Lets Write following xaml code,
Step 3:
Create a class name is "Data".
Create an object in page constructor for list of "Data" items.Add some static message contents to list object with combination of plain text and hyperlinks and finally bind list our ListBox (i.e ListBoxMessage).
Note:Here i highlighted the hyperlinks in Message.
Step 4:
In Step2,i bind the wrappanel Tag property with 'Message' and added Loaded event for wrappanel ,and we need to make some changes in code to make hyperlink action in listbox items.Loaded event will be fire when ListBox userinterface is started to load,in this event we can get every wrapapnel Tag message.So next important step is we need to detect hyperlinks from every message.After detecting the hyperlink we need to set that hyperlink to HyperlinkButton and add to wrappanel,and also add TextBlock for plaintext.So the whole code is like following.
- Open Visual Studio
- Create new project name(Ex: "ListBoxWithHyperLinks")
In DataTemplate of Listbox,I taken WrapPanel which is great for laying out things in a vertical or horizontal orientation until you reach the edge of the container and then moving on to the next column or row.In xaml code i added Loaded event for wrappanel ,so that in Loaded event fire i can detect hyperlinks from bindable message content as well as i can set action for hyperlinks by adding HyperlinkButton to wrappanel.
To use WrapPanel ,we need add Microsoft.Phone.Controls.Toolkit.dll references . And make sure the DLL is added to the references as in the following:
Open MainPage.xaml and add the toolkit namespace in xaml:
- xmlns:Toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
Lets Write following xaml code,
- <Grid x:Name="LayoutRoot" Background="White">
- <Grid.RowDefinitions>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="*"/>
- </Grid.RowDefinitions>
- <!--TitlePanel contains the name of the application and page title-->
- <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
- <TextBlock x:Name="ApplicationTitle" FontSize="25" Text="ListBoxItem with Hyperlinks Demo:" Foreground="#FF0FAEEA" />
- </StackPanel>
- <Grid Grid.Row="1">
- <!--ListBox Content.-->
- <ListBox Foreground="Black" SelectionMode="Multiple" ScrollViewer.VerticalScrollBarVisibility="Auto" Margin="5" Name="ListBoxMessage" BorderBrush="#FFE622E6" BorderThickness="3" >
- <ListBox.ItemTemplate>
- <DataTemplate>
- <Grid Height="auto" Background="White" Width="470" >
- <Grid.RowDefinitions>
- <RowDefinition Height="auto" />
- <RowDefinition Height="auto" />
- </Grid.RowDefinitions>
- <!--WrapPanel for aligning dynamic TextBlock and HyperLinkButton -->
- <Grid Grid.Row="0" MinHeight="45" VerticalAlignment="Center">
- <Toolkit:WrapPanel VerticalAlignment="Center" HorizontalAlignment="Left" Tag="{Binding Message}" Width="450" Loaded="WrapPanel_Loaded"/>
- </Grid>
- <!--ListBox Item Seperator -->
- <Rectangle Grid.Row="1" Margin="0,3,0,0" Width="500" Height="3" Fill="#FF77EEA2" HorizontalAlignment="Left"/>
- </Grid>
- </DataTemplate>
- </ListBox.ItemTemplate>
- </ListBox>
- </Grid>
Step 3:
Create a class name is "Data".
- public class Data
- {
- public string Message { get; set; }//for storing message content's
- }
Create an object in page constructor for list of "Data" items.Add some static message contents to list object with combination of plain text and hyperlinks and finally bind list our ListBox (i.e ListBoxMessage).
- // Constructor
- public MainPage()
- {
- InitializeComponent();
- List<Data> ObjDataList = new List<Data>();//for list of Data items
- //List item with plain text
- ObjDataList.Add(new Data { Message = "SubramanyamRaju WindowsPhone Tutorials is my personal blog ,which is targeted to both beginners and experience" });
- //List item with plain text and hyperlinks
- ObjDataList.Add(new Data { Message = "SubramanyamRaju WindowsPhone Tutorials blog website link : http://bsubramanyamraju.blogspot.com which is dedicated for only windowsphone development." });
- ObjDataList.Add(new Data { Message = "Windows developer blog website link :http://blogs.windows.com/buildingapps/" });
- ObjDataList.Add(new Data { Message = "https://bing.com is a search engine that brings together the best of search and people in your social networks to help you spend less time searching and more time doing." });
- ObjDataList.Add(new Data { Message = "The most popular search engines are https://bing.com and http://google.com" });
- //Bind listitem to our ListBox
- ListBoxMessage.ItemsSource = ObjDataList;
- }
Note:Here i highlighted the hyperlinks in Message.
Step 4:
In Step2,i bind the wrappanel Tag property with 'Message' and added Loaded event for wrappanel ,and we need to make some changes in code to make hyperlink action in listbox items.Loaded event will be fire when ListBox userinterface is started to load,in this event we can get every wrapapnel Tag message.So next important step is we need to detect hyperlinks from every message.After detecting the hyperlink we need to set that hyperlink to HyperlinkButton and add to wrappanel,and also add TextBlock for plaintext.So the whole code is like following.
- private void WrapPanel_Loaded(object sender, RoutedEventArgs e)
- {
- var objWrapPanel = sender as WrapPanel;
- //Clear wrapanel child items before set content
- objWrapPanel.Children.Clear();
- //Get current listboxitem message with Tag property
- string Value = Convert.ToString(objWrapPanel.Tag);
- //Check if message having http:// or https://
- if (Value.Contains("http://") || Value.Contains("https://"))
- {
- string[] SplitDataSync = Regex.Split(Value, @"(?=http)");//Split message based on http
- for (int i = 0; i < SplitDataSync.Length; i++)
- {
- var normalText = SplitDataSync[i].ToString();
- if (normalText.Contains("http"))
- {
- string navigateLink = "";
- string regUrl = @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?";
- Regex r = new Regex(regUrl);
- MatchCollection results = r.Matches(normalText);//get collection of hyperlinks from given message list item
- foreach (Match m in results)//Loop all http links from push message
- {
- navigateLink = m.Value.ToString();
- break;
- }
- var plainText = normalText.Replace(navigateLink, "");//remove http or https links from message and get plain text only
- HyperlinkButton hyper = new HyperlinkButton();//for making hyperlinkbutton when link found on message
- hyper.HorizontalAlignment = HorizontalAlignment.Left;
- hyper.FontSize = 18;
- hyper.Foreground = new SolidColorBrush(Colors.Blue);
- hyper.NavigateUri = new Uri(navigateLink);
- hyper.TargetName = "_blank";
- hyper.Margin = new Thickness(-8, 0, 0, 0);
- hyper.Content = navigateLink;//set hyperlink to hyperlinkbutton
- objWrapPanel.Children.Add(hyper); //add http link as HyperlinkButton to wrappanel
- AddTextBlocktoWrapPanel(objWrapPanel, plainText);//add plain text as TextBlock
- }
- else
- {
- AddTextBlocktoWrapPanel(objWrapPanel, normalText);//add plain text as TextBlock
- }
- }
- }
- else
- {
- AddTextBlocktoWrapPanel(objWrapPanel, Value);//add plain text as TextBlock
- }
- }
- //Add plain text as TextBlock to WrapPanel
- private void AddTextBlocktoWrapPanel(WrapPanel objWrapPanel, string Text)
- {
- TextBlock objBlock = new TextBlock();
- objBlock.Text = Text.Trim();
- objBlock.MaxWidth = 420;
- objBlock.Foreground = new SolidColorBrush(Colors.Gray);
- objBlock.TextWrapping = TextWrapping.Wrap;
- objWrapPanel.Children.Add(objBlock);
- }
ScreenShots:
After running the sample,we will get screen like this.
See in above screen when tap on blue hyperlink from ListboxItem ,it will be redirect to linked page.
FeedBack Note:
Please share your thoughts,what you think about this post,Is this post really helpful for you?and please tell me is there any alternative to make this sample.I always welcome if you drop comments on this post and it would be impressive.
FeedBack Note:
Follow me always at @Subramanyam_B
Have a nice day by Subramanyam Raju :)
Follow me always at @Subramanyam_B
Have a nice day by Subramanyam Raju :)
No comments:
Post a Comment