[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Data Template in wpf

Posted on 2011-10-03
7
Medium Priority
?
465 Views
Last Modified: 2013-11-12
Hi,

Im trying to create a custom control in wpf which will be used to display a list of custom objects

i have a list of these objects in my user control class called penalties.

the following code is on the xaml:

<ListBox ItemsSource="{Binding Penalties}" Grid.RowSpan="2" Grid.Row="2" Name="lstTest">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock FontWeight="Bold" Text="{Binding Team}" />
                        <TextBlock Text=" - " />
                        <TextBlock Text="{Binding TimeLeft}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

Open in new window


and the following is in the c#

private List<IceHockeyPenalty> penalties = null;

        public List<IceHockeyPenalty> Penalties
        {
            get { return penalties; }
            set { penalties = value; }
        }

        public PenaltyInfoControl()
        {
            InitializeComponent();
            this.penalties = new List<IceHockeyPenalty>();
            base.DataContext = penalties;
            lstTest.ItemsSource = penalties;
        }

        public void addPenaltyInfo(IceHockeyPenalty penaltyInfo)
        {
            penalties.Add(penaltyInfo);
        }

Open in new window


but nothing appears in the list when i add a new penalty

I've tried different variations of the above but no luck, can somebody tell me what i'm missing?

Thanks
0
Comment
Question by:basil365
  • 3
  • 3
7 Comments
 
LVL 7

Assisted Solution

by:vbigham
vbigham earned 400 total points
ID: 36906468
Instead of List<IceHockeyPenalty>, try using ObservableCollection<IceHockeyPenalty>.

That type of collection will report when its items have changed, and update the list box accordingly.

http://msdn.microsoft.com/en-us/library/ms668604.aspx
0
 
LVL 8

Expert Comment

by:jagrut_patel
ID: 36907923
Try this.

private List<IceHockeyPenalty> penalties = null;

public PenaltyInfoControl()
{
  InitializeComponent();
  this.penalties = new List<IceHockeyPenalty>();
  this.DataContext = new { Penalties = penalties };
}

Open in new window


<ListBox ItemsSource="{Binding Penalties}" Grid.RowSpan="2" Grid.Row="2" Name="lstTest">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock FontWeight="Bold" Text="{Binding Team}" />
                        <TextBlock Text=" - " />
                        <TextBlock Text="{Binding TimeLeft}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox> 

Open in new window


Items in List<T> will be shown in the control once when the databinding happens. Any additions to the List<T> at run-time won't be reflected into the control. If your need is to add items to ListBox at run-time then as @vbigham mentioned you can change to ObservableCollection<T> instead of List<T>.
0
 

Author Comment

by:basil365
ID: 36908574
Thanks to you both, that works for the 'team' attribute on the icehockeypenalty object - it displays in the listbox correctly.

The 'timeLeft' attribute is slightly different in that in gets updated internally by a timer. The attribute itself is simply a string also, but no value gets printed on my data template.

this is the iceHockeyPenalty class:
public class IceHockeyPenalty
    {
        TimeSpan penaltyTime;
        DispatcherTimer timer;
        TimeSpan timerInterval = new TimeSpan(0, 0, 1);
        bool isValidPenalty;
        string team;
        string timeLeft;

        public string TimeLeft
        {
          get { return timeLeft; }
        }

        public string Team
        {
            get { return team; }
        }

        public IceHockeyPenalty(TimeSpan penaltyTime,string team)
        {
            this.team = team;
            this.penaltyTime = penaltyTime;
            timer = new DispatcherTimer();
            timer.Interval = timerInterval;
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
            isValidPenalty = true;
        }

        void timer_Tick(object sender, EventArgs e)
        {
            //reduce the penalty time left
            penaltyTime = penaltyTime.Subtract(timerInterval);

            //make sure this peno is not counted if its not valid
            if (penaltyTime <= new TimeSpan(0, 0, 0))
                isValidPenalty = false;

            timeLeft = penaltyTime.Minutes + ":" + penaltyTime.Seconds;
        }

        public void extendPenalty(int minutes)
        {
            this.penaltyTime.Add(new TimeSpan(0,minutes,0));
        }

    }

Open in new window

0
Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

 
LVL 8

Expert Comment

by:jagrut_patel
ID: 36908741
Did you changed to ObservableCollection?
0
 

Author Comment

by:basil365
ID: 36908806
I did, that seems to just update if the collection changes - not if the internal objects of that collection change?

I'm looking at IObserver<T> at the moment but its current out of my grasp
0
 
LVL 8

Accepted Solution

by:
jagrut_patel earned 1600 total points
ID: 36908839
You're right. Your object "IceHockeyPenalty" needs to implement INotifyPropertyChanged.
See this example.
0
 

Author Closing Comment

by:basil365
ID: 36909051
thanks very much
0

Featured Post

Transaction-level recovery for Oracle database

Veeam Explore for Oracle delivers low RTOs and RPOs with agentless transaction log backup and transaction-level recovery of Oracle databases. You can restore the database to a precise point in time, even to a specific transaction.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes how to add a user-defined command button to the Windows 7 Explorer toolbar.  In the previous article (http://www.experts-exchange.com/A_2172.html), we saw how to put the Delete button back there where it belongs.  "Delete" is …
In this article, I will show how to use the Ribbon IDs Tool Window to assign the built-in Office icons to a ribbon button.  This tool will help us to find the OfficeImageId that corresponds to our desired built-in Office icon. The tool is part of…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
As many of you are aware about Scanpst.exe utility which is owned by Microsoft itself to repair inaccessible or damaged PST files, but the question is do you really think Scanpst.exe is capable to repair all sorts of PST related corruption issues?

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question