Unable binding thumbnail of youtube video - wpf

I could not load images of thumbnail youtube.
Class file:
public class YoutubeVideo
{
public string id { get; set; }
public string title { get; set; }
public DateTime pubdate { get; set; }
public Uri youtubelink { get; set; }
public Uri videolink { get; set; }
public Uri thumbnail { get; set; }
}
On mainpage.xaml:
<DataTemplate>
<StackPanel>
<Image Source="{Binding thumbnail}"></Image>
<TextBlock Text="{Binding title}" FontSize="10" Foreground="#cc181e" TextWrapping="Wrap"></TextBlock>
<Grid>
</Grid>
</StackPanel>
</DataTemplate>
It just show title.

After looking at your code here is the solution
change
video.id = item.Id.Remove(0, 27);
to
video.id = item.Id.Substring(item.Id.LastIndexOf("/") + 1);
that should produce the correct id of the video
the id of the video is the last few chars
eg
http://gdata.youtube.com/feeds/base/videos/_OBlgSz8sSM

Related

How to bind a control value to another source

I have a ListView which is populated with a collection called Files(ObservableCollection FileViewModel ), also I have another SelectedFiles(List Guid ) which hold the selected files id in it, how can I bind this to the UI to show the selected files with checkbox control.
Xaml:
<ListView Grid.Column="0" Grid.Row="2" Name="lstSourceFiles" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<ListView.ItemTemplate>
<DataTemplate>
<WrapPanel>
<CheckBox></CheckBox>
<TextBlock Text="{Binding Name}"></TextBlock>
</WrapPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Code:
public List<Guid> SelectedSourceFiles { get; set; }
public ObservableCollection<FileViewModel> Files { get; set; }
public class FileViewModel
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public partial class MainWindow : Window
{
public List<Guid> SelectedSourceFiles { get; set; }
public MainWindow()
{
AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(TreeItemSelected), true);
}
private void TreeItemSelected(object sender, RoutedEventArgs e)
{
var item = e.OriginalSource as TreeViewItem;
if (item == null)
{ return; }
var folder = item.DataContext as FolderViewModel;
if (folder == null)
{ return; }
if (!folder.IsFilesLoaded)
{
FileManager.LoadFiles(folder);
}
lstSourceFiles.ItemsSource = folder.Files;
}
}
The easiest way would be to add an "IsSelected" property to the view model:
public class FileViewModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
Loop through and set the property:
foreach (var file in folder.Files)
file.IsSelected = (SelectedSourceFiles.Contains(file.Guid);
And then of course bind to it:
<CheckBox IsChecked="{Binding IsSelected}" />
An alternate to the above would be to bind to the GUID and use IValueConverter that checks against the the selected list.

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.

WP7 ListBox Binding Doesn't Update

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.

How do I sort a WPF treeview that has items bound to the properties of an Item subclass?

I have two classes,
public class BookItem
{
public string BookID { get; set; }
public string ItemID { get; set; }
public Item Item { get; set; }
public ItemType Type { get; set; }
public string ParentID { get; set; }
public string BoxID { get; set; }
public string StyleID { get; set; }
public string NotesID { get; set; }
public string Code_XAML { get; set; }
public string Description_XAML { get; set; }
public CompositeCollection SubItems { get; set; }
}
public class Item : ClaunchBaseClass
{
public string ItemID { get; set; }
public int Type { get; set; }
public string Code { get; set; }
public string Description { get; set; }
private BookList _books = new BookList();
public BookList Books { get {return _books;} set { _books = value; }}
}
and I've created the following XAML:
<pre>
<TreeView Name="tvList" Grid.Row="2" MouseDoubleClick="tvList_MouseDoubleClick">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="x:Type j:BookItem" ItemsSource="{Binding SubMenu}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Item.Code}" Grid.Column="0" />
<TextBlock Text="{Binding Item.Description}" Grid.Column="1"/>
</Grid>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
<code>
This XAML binds the treeview items to the collection of book items and displays the Item subclass's Description and Code, the treeview populates and displays correctly but now I want to sort the treeview on either Item.Code or Item.Description and have tried the following with no results:
<pre>
var bookItemsSort = CollectionViewSource.GetDefaultView(_bookItemList) as ListCollectionView;
tvList.ItemsSource = _bookItemList; //bind the book items to the treeview
bookItemsSort.SortDescriptions.Clear();
bookItemsSort.SortDescriptions.Add(new SortDescription(sort, Ascending));
<code>
I've had this code work correctly for other treeviews so I can only guess it is a problem with binding to a subclass.
While the answers here provided partial answers to my question, none of them gave the answer that I needed.
The most sensible solution for this problem was to write my own object comparer for this object type and sort the underlying list and then re-bind the new list to the treeview. This allowed for comparing sublasses at any nested level which I couldn't make work any other way :)
You need to get the default view for each sub-list, and apply a CollectionViewSource sorting to it. The code you posted only affects the top level items.
Bind your TreeView.ItemsSource to the DefaultView. SortDescriptions will not change your DataList, only the View of it.
tvList.ItemsSource = bookItemsSort;
See Bea Stollnitz blog: How can I sort a hierarchy?

Silverlight printing with ListBox

I need to print a complex document with paging from silverlight. Ihave found a good project from http://silverlightreporting.codeplex.com/. Playing with this example, i have found, that more complex templates works not correctly:
I have add a ChildNames property:
public class EmployeeReviewReportItem
{
public string LastName { get; set; }
public string FirstName { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public int PerformanceRating { get; set; }
public decimal Salary { get; set; }
public decimal Bonus { get; set; }
public string ReviewComments { get; set; }
public string[] ChildNames { set; get; }
}
in ReportData.cs set value for this property:
ChildNames = new string[] { firstNames.Random(), firstNames.Random(), firstNames.Random() }
and then in MainPage.xaml a new ListBox to show this prperty:
...
<TextBlock Grid.Row="2"
Grid.ColumnSpan="4"
TextWrapping="Wrap"
Text="{Binding ReviewComments}" />
<ListBox Grid.Row="3" Grid.ColumnSpan="4" ItemsSource="{Binding ChildNames}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Width="300"
Height="auto"
VerticalAlignment="Top"
Text="{Binding .}"
TextWrapping="Wrap" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
...
ListBox will be rendered without content.
How i can get Child names printed?
Does {Binding .} work? I've never seen it (of course that doesn't mean it isn't correct). I would just use {Binding} instead. If that doesn't work then you can try changing string[] to ObservableCollection<string> and also make the binding a twoway binding: ItemsSource="{Binding ChildNames, Mode=TwoWay}".
Without seeing the complete source code, I can't really help much more than this.

Resources