DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Using the Coding4Fun ChatBubble and ChatBubbleTextBox in a Windows Phone Application

Denzel D. user avatar by
Denzel D.
·
Apr. 01, 12 · Interview
Like (0)
Save
Tweet
Share
15.29K Views

Join the DZone community and get the full member experience.

Join For Free

recently checked in a new release of the Coding4Fun Toolkit for Windows Phone that introduces the ChatBubble and ChatBubbleTextBox controls. With the help of the above mentioned additions it is possible to replicate the Windows Phone Messaging user interface.

ChatBubble is a container that can be used to show any kind of visual content in the form of a chat bubble. A ChatBubbleTextBox is used to receive user input. Instead of giving you a boring example listing the properties of the controls, let's create a messaging interface simulation.

Here is a grid split into three rows - the top one is designated for the contact name, the bottom one is where the text to be sent is entered, and the middle one - that's where the messages show up.

<phone:PhoneApplicationPage 
    x:Class="RingtoneFeeder.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    xmlns:cc="clr-namespace:Coding4Fun.Phone.Controls;assembly=Coding4Fun.Phone.Controls" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" d:DesignHeight="800" d:DesignWidth="480">

    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="550"></RowDefinition>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="PageTitle" Text="den d." Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <cc:ChatBubble ChatBubbleDirection="LowerRight">
             Test   
            </cc:ChatBubble>
        </StackPanel>

        <StackPanel Margin="12,0,12,12" Grid.Row="2" Orientation="Horizontal">
            <cc:ChatBubbleTextBox Margin="0,6,0,0" ChatBubbleDirection="LowerRight" TextWrapping="Wrap" Width="340"></cc:ChatBubbleTextBox>
            <Button Content="Send"></Button>
        </StackPanel>
    </Grid>
</phone:PhoneApplicationPage>

It looks like this in the emulator:

This is a pretty static interface - there is not a lot of action going on here. You can see that the ChatBubble control has the ChatBubbleDirection property, that determines where the chat handler (the little triangle in the corner of a bubble) is shown. The same applies to ChatBubbleTextBox. Currently, I am using a single ChatBubble instance that has text set as its content. However, there are more chat messages that might be coming in, so it would make more sense to use a ListBox with a custom DataTemplate that is a ChatBubble control.

As you probably know, a text message sent through the Messaging Hub on a Windows Phone also contains the date it was sent, so let's have a Grid control in the ChatBubble, split into two rows - one for the text message and another one for the date:

<cc:ChatBubble  Margin="0,0,0,20" ChatBubbleDirection="LowerRight">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="40"></RowDefinition>
        </Grid.RowDefinitions>
        
        <TextBlock Text="Testing the capabilities." TextWrapping="Wrap" Width="430"></TextBlock>
        
        <TextBlock Grid.Row="1" HorizontalAlignment="Right" Text="12/12/12"></TextBlock>
    </Grid>
</cc:ChatBubble>

This way, I am easily achieving the following look:

But there is no model for the Message, so let's create one. Add a class to the project and name it Message.cs. In that class, you need two string properties - Text and SendingDate.

public class Message
{
    public string Text { get; set; }
    public string SendingDate { get; set; }
}

Going back to the data model XAML, let's bind the TextBlock controls to the properties in this Message class:

<Grid Width="456">
    <cc:ChatBubble Width="340" Margin="0,0,0,20">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="40"></RowDefinition>
            </Grid.RowDefinitions>

            <TextBlock Text="{Binding Text}" TextWrapping="Wrap" Width="430"></TextBlock>

            <TextBlock Grid.Row="1" HorizontalAlignment="Right" Text="{Binding SendingDate}"></TextBlock>
        </Grid>
    </cc:ChatBubble>
</Grid>

This data model should be integrated in a ListBox, as an ItemTemplate:

<ListBox>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid Width="456">
                <cc:ChatBubble Width="340" Margin="0,0,0,20">
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"></RowDefinition>
                            <RowDefinition Height="40"></RowDefinition>
                        </Grid.RowDefinitions>

                        <TextBlock Text="{Binding Text}" TextWrapping="Wrap" Width="430"></TextBlock>

                        <TextBlock Grid.Row="1" HorizontalAlignment="Right" Text="{Binding SendingDate}"></TextBlock>
                    </Grid>
                </cc:ChatBubble>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

The list above, however, will be empty, as there is no binding for ItemsSource. To fix this, I created a central binding class that follows the pattern I described in this article.

Notice that I am using an ObservableCollection<Message> for convenient re-binding when the collection is updated.

using System;
using System.Windows;
using System.ComponentModel;
using System.Collections.ObjectModel;

namespace RingtoneFeeder
{
    public class Binder : INotifyPropertyChanged
    {
        static Binder instance = null;
        static readonly object padlock = new object();

        public Binder()
        {
            Messages = new ObservableCollection<Message>();
        }

        public static Binder Instance
        {
            get
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new Binder();
                    }
                    return instance;
                }
            }
        }

        private ObservableCollection<Message> messages;
        public ObservableCollection<Message> Messages
        {
            get
            {
                return messages;
            }
            set
            {
                if (messages != value)
                {
                    messages = value;
                    NotifyPropertyChanged("Messages");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => { PropertyChanged(this, new PropertyChangedEventArgs(info)); });
            }
        }
    }
}

This class is exposed through a resource in App.xaml:

<Application 
    x:Class="RingtoneFeeder.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"       
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:local="clr-namespace:RingtoneFeeder">

    <Application.Resources>
        <local:Binder x:Key="Binder"></local:Binder>
    </Application.Resources>

    <Application.ApplicationLifetimeObjects>
        <shell:PhoneApplicationService 
            Launching="Application_Launching" Closing="Application_Closing" 
            Activated="Application_Activated" Deactivated="Application_Deactivated"/>
    </Application.ApplicationLifetimeObjects>
</Application>

Now I can bind the ListBox to the main message collection:

<ListBox ItemsSource="{Binding Path=Instance.Messages,Source={StaticResource Binder}}">

Now let's make sure that when the user clicks on the Send button, the message is added to the collection. I named the ChatBubbleTextBox as txtMessage and the button btnSend.

private void btnSend_Click(object sender, RoutedEventArgs e)
{
    if (!string.IsNullOrEmpty(txtMessage.Text))
    {
        Message message = new Message()
        {
            Text = txtMessage.Text,
            SendingDate = DateTime.Now.ToShortDateString()
        };

        Binder.Instance.Messages.Add(message);
        txtMessage.Text = string.Empty;
    }
}

Let's see what we get now:

There is one problem, however. If you look at the actual Messaging Hub, you will notice that both the direction of the chat handler (again, that little triangle in the corner) and the shade of the main color switch between messages sent by the phone owner and those sent by the conversation partner.

In my simulation, let's assume that every second message is actually a response. I will need to modify the ChatBubbleDirection, Alignment and Opacity properties depending on the sender. This can easily be done based on the index of the message in the collection, and I built a custom converter to detect just that:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    int ival = Binder.Instance.Messages.IndexOf((Message)value);

    // Checks the modulus, whether the index is odd or even
    if (ival % 2 == 0)
    {
        if (parameter == null)
            return 1; // no parameter - return opacity
        else
        {
            if (parameter.ToString() == "direction") // return chat "triangle" direction
            {
                return ChatBubbleDirection.LowerRight;
            }
            else  // return aligment
            {
                return HorizontalAlignment.Right;
            }
        }
    }
    else
    {
        if (parameter == null)
            return .8;
        else
        {
            if (parameter.ToString() == "direction")
            {
                return ChatBubbleDirection.UpperLeft;
            }
            else
            {
                return HorizontalAlignment.Left;
            }
        }
    }
}

The binding for the ChatBubble itself looks like this:

<cc:ChatBubble Width="340" HorizontalAlignment="{Binding Converter={StaticResource MType},ConverterParameter=align}"  Opacity="{Binding Converter={StaticResource MType}}" ChatBubbleDirection="{Binding Converter={StaticResource MType},ConverterParameter=direction}" Margin="0,0,0,20">

So here is what the UI looks like now, when the messages are stored:

There you have it! If you need to download the sample project, .

Windows Phone application

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Java Development Trends 2023
  • How To Generate Code Coverage Report Using JaCoCo-Maven Plugin
  • Kotlin Is More Fun Than Java And This Is a Big Deal
  • A Complete Guide to AngularJS Testing

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: