WP7 ListBox Binding Doesn't Update - wpf

I've been sitting on this problem for hours now,
I've got this partial xaml code:
<TextBlock Text="{Binding temprature}" Height="30" HorizontalAlignment="Left" Margin="13,119,0,0" Name="textBlock1" VerticalAlignment="Top" Width="68" />
<TextBlock Height="30" HorizontalAlignment="Left" Name="commentsTextBlock" Text="Comments:" VerticalAlignment="Bottom" Margin="12,0,0,-31" />
<ListBox Margin="2,785,-14,-33" ItemsSource="{Binding comments}" DataContext="{Binding}" Name="commentsListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,0,0,17">
<StackPanel Width="311">
<TextBlock Text="{Binding poster_username}" TextWrapping="NoWrap" Style="{StaticResource PhoneTextSubtleStyle}" TextTrimming="WordEllipsis" Width="Auto" Foreground="White" FontFamily="Segoe WP Semibold" />
<TextBlock Text="{Binding comment_text}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}" TextTrimming="WordEllipsis" MaxHeight="100" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And I have this class (Thread) which include a List of comments that should be displayed in the ListBox.
public class Thread : INotifyPropertyChanged
{
public string title { get; set; }
public string deal_link { get; set; }
public string mobile_deal_link { get; set; }
public string deal_image { get; set; }
public string deal_image_highres { get; set; }
public string description { get; set; }
public string submit_time { get; set; }
public bool hot_date { get; set; }
public string poster_name { get; set; }
public double temperature { get; set; }
public double price { get; set; }
public int timestamp { get; set; }
public string expired { get; set; }
public Forum forum { get; set; }
public Category category { get; set; }
public object merchant { get; set; }
public object tags { get; set; }
public int thread_id { get; set; }
public string visit_link { get; set; }
public string hot_time { get; set; }
public int comment_count { get; set; }
public string availability { get; set; }
public string can_vote { get; set; }
public string seen { get; set; }
public List<Comment> comments { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public void Convert2Unicode()
{
UnicodeEncoding unicode = new UnicodeEncoding();
Byte[] encodedBytes = unicode.GetBytes(title);
title = String.Format("[{0}]", title);
}
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public void SetComments(string content)
{
PaginatedComments commentsList;
this.comments.Clear();
DataContractJsonSerializer serializer =
new DataContractJsonSerializer(typeof(PaginatedComments));
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(content)))
{
commentsList = (PaginatedComments)serializer.ReadObject(ms);
}
foreach (var thread in commentsList.data.comments)
{
this.comments.Add(thread);
}
}
public Thread()
{
comments = new List<Comment>();
}
public void addComments()
{
List<string> parameters = new List<string>();
parameters.Add("thread_id=" + thread_id);
parameters.Add("results_per_page=10");
parameters.Add("page=1");
// Set the data context of the listbox control to the sample data
APICalls.makeRequest(APICalls.ViewingPaginatedComments, parameters, SetComments);
}
//
// Sets the "Seen" variable depending if the item is new (since the last time the application was opened
//
public void updateNewItems()
{
try
{
int last_seen = (int)IsolatedStorageSettings.ApplicationSettings["lastrun"];
if (last_seen < timestamp)
{
seen = "New";
}
else
{
seen = "";
}
}
catch (System.Exception e)
{
IsolatedStorageSettings.ApplicationSettings["lastrun"] = APICalls.GetIntTimestamp();
IsolatedStorageSettings.ApplicationSettings.Save();
MessageBox.Show(e.Message);
}
IsolatedStorageSettings.ApplicationSettings["lastrun"] = APICalls.GetIntTimestamp();
IsolatedStorageSettings.ApplicationSettings.Save();
}
}
public class Comment
{
public string poster_username { get; set; }
public string post_date { get; set; }
public string comment_text { get; set; }
public int timestamp { get; set; }
public int like_count { get; set; }
public string comment_edit_text { get; set; }
}
public class CommentData
{
public List<Comment> comments { get; set; }
public int comment_count { get; set; }
public int total_comments { get; set; }
}
public class PaginatedComments
{
public string response_status { get; set; }
public CommentData data { get; set; }
}
If I load the comments into the Thread before changing the DataCotext to this specific thread. the comments are shown, but when I update the comments after changing the DataContext and navigating to the page the comments are not shown (I have other fields in the rest of the xaml page that are binded to the same instance and they work perfectly. only the comments don't work!
I really appreciate your help!
Thanks

You should be using
public ObservableCollection<Comment> comments{ get; set;}
instead of
public List<Comment> comments { get; set; }
The ObservableCollection sends update notices to the view anytime one of the items(in this case a Comment ) is added or removed.
Note: It won't update the Comment . To have the items bound to the Comment update, Comment has to implement INotifyPropertyChanged.

Your property is a simple List<T>. Silverlight needs to be signaled when something changes, using events.
A List<T> does not raise any event when items are being added/removed, so Silverlight cannot detect the new items and thus does not update the UI. The simplest way to make this work is usually to use an ObservableCollection<T> instead of a list.
This collection will raise events that Silverlight knows to listen to.
Please note that for this to work you should not call Add/Remove/Clear from any other thread than the U/I (Dispatcher) thread, since Silverlight controls are not thread-safe (and the events are raised on the thread that performs the Add/Remove/Clear call). To do that, simply make sure you call Dispatcher.BeginInvoke from your SetComments method (since it seems to be a callback happening from whatever your fetching mechanism is).
Alternatively, you could also regenerate a brand new List object when fetching comments, and raise the NotifyPropertyCHanged event in the SetComments method, but that would lead to losing the current selection and resetting your list to the top, which is probably not what you want to do.

Related

Error Loading UserControl

I have created a new View in my WPF Application.
When I attempt to load the View, I receive the following errors:
"An unhandled excetion of type 'System.FormatException' occurred in mscorlib.dll"
"Additional Information: Input string was not in a correct format"
"When converting a string to DateTime, parse the string to take the date before putting each variable into the DateTime object."
I know it has something to do with the LINQ to SQL query in my ViewModel, because when I comment it out, everything works; however, there are no DateTime fields in my Model.
As you can see below the model is made of of strings, int, and bool values.
Any insight into this is greatly appreciated. Thank you for your time.
Model
{
public int ID { get; set; }
public Nullable<int> employeeNumber { get; set; }
public string userName { get; set; }
public string parentBranch { get; set; }
public string branch { get; set; }
public bool ATS { get; set; }
public bool website { get; set; }
public bool admin { get; set; }
public bool HR { get; set; }
public string timesheet { get; set; }
public string debug { get; set; }
}
View
<UserControl x:Class="Craig_Tools.ApplicationTrackingSystem.Views.Security"
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"
xmlns:dg="clr-namespace:Craig_Tools.ApplicationTrackingSystem.userControls.datagrids"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<DockPanel>
<ContentControl DockPanel.Dock="Top" HorizontalAlignment="Stretch" VerticalAlignment="Top">
<dg:dg_security />
</ContentControl>
</DockPanel>
ViewModel
public partial class SecurityViewModel : ViewModelBase
{
public SecurityViewModel()
{
LoadSecurity();
}
public void LoadSecurity()
{
using (JobSeekersEntities db = new JobSeekersEntities())
{
var q = (from s in db.securities
select s).ToList();
securityList = new ObservableCollection<security>(q);
}
}
//ObservableCollections
private ObservableCollection<security> securityList;
public ObservableCollection<security> SecurityList
{
get { return securityList; }
set
{
securityList = value;
RaisePropertyChangedEvent("SecurityList");
}
}
//Constructors
private int selectedSecurity;
public int SelectedSecurity
{
get { return selectedSecurity; }
set
{
{ selectedSecurity = value; }
RaisePropertyChangedEvent("SelectedSecurity");
}
}
//Commands
}

SelectedValuePath does not return an id

Hey I have a question about getting an ContactTypeId from the ContactType. This is the object that has an id:
public class ContactType
{
public int ContactTypeId { get; set; }
public string ContactTypeValue { get; set; }
public int ContactId { get; set; }
public DateTime? Added { get; set; }
public DateTime? Updated { get; set; }
public DateTime? Deleted { get; set; }
}
I wrote a WPF application that has a listbox.
<ComboBox x:Name="ContactTypeComboBox" HorizontalAlignment="Left" Margin="110,68,0,0" VerticalAlignment="Top" Width="120" ItemsSource="{Binding ContactTypes}" DisplayMemberPath="ContactTypeValue" SelectedValuePath="ContactTypeId" />
If i get Selected value path doesn't give an ContactTypeId from that object. It only gives a string "ContactTypeId"
Please help me to get a ContactTypeId from ContactType
SelectedValuePath tells the control how to drill down into the selected item and extract a value. The value for the selected item (in this case, its ContactTypeId) is exposed as SelectedValue. That's the property you want to read.

Silverlight Telerik RadCombobox Within RadGridView Binding issue

I'm binding an editable (you can type in it to add items to the list of choices) radcombobox in a column of a radgridview. It is not throwing a binding error, but it is not updating the bound property (Model.Remarks)
Here are the classes
public class NotamRemarkList : List<string>
{
public NotamRemarkList()
{
Add("Precision approaches are down; higher weather minimums apply.");
Add("Due to runway closure, approaches available have higher minimums.");
Add("All approaches are down; weather must be VFR.");
Add("Long runway is closed; issue if the other runways are wet.");
Add("Runway shortened; issue if wet.");
Add("Airport will be closed at the time we are scheduled in.");
Add("Runway lights are inoperative; night flights prohibited.");
}
}
public class NotamViewModel
{
[DataMember]
public string NewStatus { get; set; }
[DataMember]
public Notam Model { get; set; }
[DataMember]
public string NotamGroup { get; set; }
[DataMember]
public int NotamCount { get; set; }
[DataMember]
public DateTime? EarliestNotamDepartureTime { get; set; } // min_dep_datetime
[DataMember]
public string RadioButtonGroupName { get; set; }
}
public class Notam
{
[DataMember]
public string Remarks { get; set; }
[DataMember]
public string TripNumber { get; set; }
[DataMember]
public string ArrivalDeparture { get; set; }
}
Here's the xaml I have tried for the column - the first one uses a cell template, the second attempts to do everything in a column
<telerik:GridViewDataColumn Header="Remarks" IsFilterable="False" IsSortable="False" IsReadOnly="False" Width="430">
<telerik:GridViewDataColumn.CellTemplate>
<DataTemplate>
<telerik:RadComboBox SelectedValue="{Binding Model.Remarks, Mode=TwoWay}" ItemsSource="{StaticResource NotamRemarkList}" IsEditable="True"/>
</DataTemplate>
</telerik:GridViewDataColumn.CellTemplate>
</telerik:GridViewDataColumn>
<telerik:GridViewComboBoxColumn SelectedValueMemberPath="Model.Remarks" UniqueName="colRemarks" IsComboBoxEditable="true" IsFilterable="False" IsSortable="False"/>
public class Notam:INotifyPropertyChanged
{
private string _remarks;
[DataMember]
public string Remarks
{
get {return _remarks;}
set{
_remarks=value ;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Remarks"));
}
}
[DataMember]
public string TripNumber { get; set; }
[DataMember]
public string ArrivalDeparture { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
}
<telerik:RadComboBox SelectedValue="{Binding Model.Remarks, Mode=TwoWay}" SelectedValueMemberPath="Model.Remarks" ItemsSource="{StaticResource NotamRemarkList}" IsEditable="True"/>
I hope this will help.

Binding ComboBox to Secondary Object

My page's data context is set to an Instance of a Project class and all of the other fields in the page are working properly. Each project has another class associated with it as a property. This represents data from another company that we are integrating into this page.
I am attempting to bind to this sub object's TypeID property. Here is a sketch of the objects.
public class Project
{
public int Id { get; set; }
public string ProjectName { get; set; }
public ABCProject ABCProject { get; set; }
}
public class ABCProject
{
public int Id { get; set; }
public int ABCProjectTypeId { get; set; }
public ABCProjectType { get; set; }
}
public class ABCProjectType
{
public int ProjectTypeId { get; set; }
public string TypeName { get; set; }
}
Here is what my XAML looks like:
<telerik:RadComboBox Grid.Column="2" Grid.Row="1" telerik:StyleManager.Theme="Metro" x:Name="ProjectTypeCombo"
ItemsSource="{Binding ProjectTypePickList}"
SelectedValue="{Binding ABCProject.ABCProjectTypeId, Mode=TwoWay}"
SelectedValuePath="ABCProjectTypeId"
DisplayMemberPath="TypeName"/>
The pick list is being bound properly. The issue is that the selected value and selected value path don't seem to be binding as I get a blank combobox when the page loads.

Binding to ItemsSource not working until visual element is manually inspected (MVVM)

I have the Xaml which should basically bind a set of ContextualButtons for a selected tab's viewmodel to the ItemsSource property of the ToolBar. For some reason, this binding is not actually occuring unless I use Snoop to inspect the element manually...It seems that the act of snooping the element is somehow requerying the binding somehow.
Does anyone know what I might be doing wrong here? This behavior is the same if I use a Listbox as well, so I know it is something that I am doing incorrectly...but I am not sure what.
SelectedView is a bound property to the selected view from a Xam Tab control.
XAML
<ToolBar DataContext="{Binding SelectedView.ViewModel}"
ItemsSource="{Binding ContextualButtons}" >
<ToolBar.ItemTemplate>
<DataTemplate>
<!-- <Button ToolTip="{Binding Name}"-->
<!-- Command="{Binding Command}">-->
<!-- <Button.Content>-->
<!-- <Image Width="32" Height="32" Source="{Binding ImageSource}"/>-->
<!-- </Button.Content>-->
<!-- </Button>-->
<Button Content="{Binding Name}"/>
</DataTemplate>
</ToolBar.ItemTemplate>
</ToolBar>
Code
public class TestViewModel : BaseViewModel, IBulkToolViewModel
{
public TestViewModel()
{
ContextualButtons = new ObservableCollection<IContextualButton>()
{
new ContextualButton("Test Button",
new DelegateCommand<object>(
o_ => Trace.WriteLine("Called Test Button")), String.Empty)
};
}
public string Key { get; set; }
private ObservableCollection<IContextualButton> _contextualButtons;
public ObservableCollection<IContextualButton> ContextualButtons
{
get { return _contextualButtons; }
set
{
if (_contextualButtons == value) return;
_contextualButtons = value;
//OnPropertyChanged("ContextualButtons");
}
}
}
public partial class TestView : UserControl, IBulkToolView
{
public TestView()
{
InitializeComponent();
}
public IBulkToolViewModel ViewModel { get; set; }
}
public class ContextualButton : IContextualButton
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
public ICommand Command { get; set; }
public string ImageSource { get; set; }
public ContextualButton(string name_, ICommand command_, string imageSource_)
{
Name = name_;
Command = command_;
ImageSource = imageSource_;
}
}
public class BulkToolShellViewModel : BaseViewModel, IBaseToolShellViewModel, IViewModel
{
private IBulkToolView _selectedView;
public IBulkToolView SelectedView
{
get
{
return _selectedView;
}
set
{
if (_selectedView == value) return;
_selectedView = value;
OnPropertyChanged("SelectedView");
}
}
public ObservableCollection<IBulkToolView> Views { get; set; }
public DelegateCommand<object> AddViewCommand { get; private set; }
public DelegateCommand<object> OpenPortfolioCommand { get; private set; }
public DelegateCommand<object> SavePortfolioCommand { get; private set; }
public DelegateCommand<object> GetHelpCommand { get; private set; }
public BulkToolShellViewModel(ObservableCollection<IBulkToolView> views_)
: this()
{
Views = views_;
}
public BulkToolShellViewModel()
{
Views = new ObservableCollection<IBulkToolView>();
AddViewCommand = new DelegateCommand<object>(o_ => Views.Add(new TestView
{
ViewModel = new TestViewModel()
}));
OpenPortfolioCommand = new DelegateCommand<object>(OpenPortfolio);
SavePortfolioCommand = new DelegateCommand<object>(SavePortfolio);
GetHelpCommand = new DelegateCommand<object>(GetHelp);
}
private void GetHelp(object obj_)
{
}
private void SavePortfolio(object obj_)
{
}
private void OpenPortfolio(object obj_)
{
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged()
{
throw new NotImplementedException();
}
public void RaisePropertyChanged(string propertyName)
{
throw new NotImplementedException();
}
public string this[string columnName]
{
get { throw new NotImplementedException(); }
}
public string Error { get; private set; }
public AsyncContext Async { get; private set; }
public XmlLanguage Language { get; private set; }
public string Key { get; set; }
}
Thanks!
Why does BulkToolShellViewModel have its own PropertyChanged event along with RaisePropertyChanged methods that do nothing? Shouldn't it inherit this functionality from BaseViewModel? Perhaps the UI is attaching to BulkToolShellViewModel.PropertyChanged rather than BaseViewModel.PropertyChanged and is never being notified of changes.

Resources