c# link objects wrapped on the listbox in WINDOWS PHONE - c#

I have this block of code as you can see in the screen print correctly loads the data you want and store the list of objects PopularVideos:
item { Title = Hey Porsche, Url = http://www.unnu.com/wp-content/plugins/wordpress-popular-posts/timthumb.php?src=http://www.unnu.com/wp-content/uploads/2013/03/019.jpg&h=65&w=275 } <>f__AnonymousType0<string,string>
item.Title "Hey Porsche" string
item.Url "http://www.unnu.com/wp-content/plugins/wordpress-popular-posts/timthumb.php?src=http://www.unnu.com/wp-content/uploads/2013/03/019.jpg&h=65&w=275" string
Need to load these objects in my list box with binding or has otherwise also can be. But the windows phone does not work with DataSource and DisplayMember.
My XAML:
<ListBox Name="listBoxPopular">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Name="imagem" Source="{Binding Path=Url}"/>
<TextBlock Text="{Binding Titulo}" Tap="HyperlinkButton_Tap" FontSize="30" Foreground="#FF159DDE" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</controls:PanoramaItem>
My Class is:
class PopularVideos
{
public PopularVideos() { }
public PopularVideos(string titulo, string url)
{
Titulo = titulo;
BitmapImage Img = new BitmapImage(new Uri(url));
}
public string Titulo { get; set; }
public Uri Url { get; set; }
}
and my codebehind is:
_popVideos = new List<PopularVideos>();
var data = e.Document.DocumentNode.SelectSingleNode("//div[#class='content']")
.Descendants("img")
.Select(img => new
{
Title = img.Attributes["alt"].Value,
Url = img.Attributes["src"].Value,
}).ToList();
foreach (var item in data)
{
PopularVideos pop = new PopularVideos(item.Title, item.Url);
_popVideos.Add(new PopularVideos(item.Title, item.Url));
}
listBoxPopular.ItemsSource = _popVideos;
This code works because they are carrying the images and links in the objects, just can not bring up in my list box.

Have a bindable ObservableCollection<Item> (preferrably in a ViewModel).
Use the ListBox.ItemsSource property to bind to said ObservableCollection<Item>. The standard binding rules apply.
Each of the items in ListBox will be a representation of the items in the core collection that is bound to the control, so bind to its properties the same way you would to anything else.

It's reply to comment:
Ok, please read once again the article that #Den send to you. And please remove DataContext Property from ListBox, add x:Name="myList" to ListBox and in code-behind: myList.DataContext = this; This is not the best solution, but it's easy to understand and firstly you need to understand it :) Best regards.

Related

xamarin forms how to populate picker from code behind

Evening All,
Learning Xamarin forms..attempting to add a picker with numeric values...(using https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/picker/populating-itemssource)
I have used the example on this page to get the picker populated from the view...which works fine...however I want to populate the picker from code behind...
<---XAML--->
<Picker Grid.Column="4" Grid.Row="2" ItemsSource="{Binding pickerSource}"/>
<---c#---->
var pickerList = new List<string>();
pickerList.Add("1");
pickerList.Add("2");
pickerList.Add("3");
pickerList.Add("4");
pickerList.Add("5");
pickerList.Add("6");
pickerList.Add("7");
pickerList.Add("8");
pickerList.Add("9");
pickerList.Add("10");
var pickerSource = new Picker { Title = "Quantity", TitleColor = Color.Red };
pickerSource.ItemsSource = pickerList;
Picker is appearing on app but when selected, its not populated with any values...why isnt this binding properly anyone?
Thank you
Also...as a side note if anyone is aware of a tool that contains all numeric values instead of me manually having to populate it with 1,2,3 etc..
Thanks Again
Thanks to #Jason for the reply...From here I have went with the following:
---xaml--
<Picker Grid.Column="4" Grid.Row="2" ItemsSource="{Binding pickerSource}"/>
---c#----
public List<string> pickerSource { get; set; }
public void PopulateQuantityPicker()
{
var pickerList = new List<string>();
pickerList.Add("1");
pickerList.Add("2");
pickerList.Add("3");
pickerList.Add("4");
pickerList.Add("5");
pickerList.Add("6");
pickerList.Add("7");
pickerList.Add("8");
pickerList.Add("9");
pickerList.Add("10");
pickerSource = pickerList;
this.BindingContext = this;
}
The picker is on the app, but it is not populated, it is empty.
When I Click on it I get the following:
(also the code is hitting the PopulateQuantityPicker())
here you are binding your ItemsSource to pickerSource
<Picker Grid.Column="4" Grid.Row="2" ItemsSource="{Binding pickerSource}"/>
in your code behind, you need a public property named pickerSource. You can only bind to public properties
public List<string> pickerSource { get; set }
// assign the data to your ItemsSource
pickerSource = pickerList;
// also be sure to set the BindingContext
BindingContext = this;
// this is creating a new picker named pickerSource. You have already done
// this in your XAML. This is NOT NEEDED
var pickerSource = new Picker { Title = "Quantity", TitleColor = Color.Red };
pickerSource.ItemsSource = pickerList;
if you want to do this from the code behind WITHOUT using binding, you first need to assign an x:name to your control
<Picker x:Name="myPicker" Grid.Column="4" Grid.Row="2" />
then in the code behind
myPicker.ItemsSource = pickerList;

Textboxes don't clear themselves when page loaded

I have list of employers that binding to data and fill from special form. When I go to form I have every text boxes clear. I fill all of them and save new employer to list. But if I try to add new employer I have textboxes with previous text in form. And variables that bind to text boxes in form are all null.
Is there way to solve problem without using solution like that: Textbox.text=null;?
I'm using MVVM pattern in my app. I'm also using catel snippets to define viewmodel and properties. There is code of ViewModel of page with employer properties:
public EmployerModifyViewModel(TransferParameter parameter, IEmployersListManage employersListManager)
{
//in "parameter" I pass values fo Current employer (it can be empty
//if we need to add new object to list or it can be some employer from list)
_employersListManager = employersListManager;
SaveEmployerCommand = new Command(OnSaveEmployerCommandExecute);
CanselSavingCommand = new Command(OnCanselSavingCommandExecute);
if (parameter.Value is EmployerClass)
{
CurrentEmployer = parameter.Value as EmployerClass;
}
}
public EmployerClass CurrentEmployer
{
get { return GetValue<EmployerClass>(CurrentEmployerProperty); }
private set { SetValue(CurrentEmployerProperty, value); }
}
/// <summary>
/// Register the CurrentEmployerBase property so it is known in the class.
/// </summary>
public static readonly PropertyData CurrentEmployerProperty = RegisterProperty("CurrentEmployer", typeof(EmployerClass), new EmployerClass());
There is example of binding to properties in xaml:
<ContentControl Content="{Binding CurrentEmployer, Mode=TwoWay}">
<ContentCntrol.Recources>
<DataTemplate DataType="{x:Type employer:EmployerClass}">
...
<TextBox Grid.Column="1"
x:Name="EmpName"
Width="300"
Height="30"
FontSize="14"
Text="{Binding Name, Mode=TwoWay}" //Property "Name" of CurrentEmployer
HorizontalAlignment="Left"
Margin="20,20,0,0"/>
I think u should use the below code where u add the new employee. Everytime the button is clicked the textboxes go empty.
txtbox_1.Text = String.Empty;
txtbox_2.Text = String.Empty;
.............
Thank you for all, problem solved. I removed ContentControl and DataTemplate from xaml and I made bindings like this "{Binding CurrentEmployer.Name, Mode=TwoWay}".

C# - Using WPF to create a Two-line ListBox for each item

Im having some trouble with WPF, as its my first time usage of it.
Im trying to create a ListBox, that holds two lines for each item in it. How can i achieve this ?
I have tried the following:
<ListBox>
<Label name="first">First Line</label>
<Label name="second">Second Line</label>
</ListBox>
Even though this does not give any errors, i do not think its the correct way to do it.
Can you guys assist ?
You can achieve this by modifying the ListBox ItemTemplate, while binding to a collection of data you want to display.
Xaml:
<ListBox Name="MyListBox" ItemsSource="{Binding ListBoxData}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Text1}" MinWidth="200"/>
<TextBlock Text="{Binding Text2}" MinWidth="200"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Xaml.cs:
namespace WpfApplication1
{
public partial class MainWindow
{
public List<MyRow> ListBoxData { get; set; }
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
ListBoxData = new List<MyRow>
{
new MyRow{Text1 = "Row 1 - Data 1", Text2 = "Row 1 - Data 2"},
new MyRow{Text1 = "Row 2 - Data 1", Text2 = "Row 2 - Data 2"},
new MyRow{Text1 = "Row 3 - Data 1", Text2 = "Row 3 - Data 2"}
};
}
}
public class MyRow
{
public string Text1 { get; set; }
public string Text2 { get; set; }
}
}
In terms of WPF, you typically want to use binding rather than hard-coding items into the xaml directly. The example above shows data binding via code-behind, but ideally, you would want to create a ViewModel and bind to that. I would suggest looking up MVVM once you get more familiar w/ WPF.
You can create items in a list box like so,
<ListBox>
<ListBoxItem Name="Item1">Item</ListBoxItem>
<ListBoxItem Name="Item2">Item2</ListBoxItem>
</ListBox>
Or if you want them dynamically assigned you can set the value like so in code,
Listbox1.ItemsSource = <some collection>;
Listbox1.DisplayMemberPath = "<Collection item you want displayed>";
Or this way for MVVM pattern
<ListBox ItemsSource="{Binding Path=<Your Property>}" DisplayMemeberPath="{Binding Path =Display Value Property}" />

Why Silverlight binding doesnt work?

I have 2 listboxes populated by data like so:
GoogleNewsResults.Add(
new News()
{
Content = "News Content", Title = "News Title"
});
NotifyPropertyChanged("GoogleNewsResults");
GoogleBlogsResults.Add(
new Blog()
{
Content = "Blog Content", Title = "Blog Title"
});
NotifyPropertyChanged("GoogleBlogsResults");
But it doesnt update Blog Results listbox. Do you have any idea why?
The XAML has this type of binding:
<sllb:ListBox x:Name="GoogleBlogsList" ItemsSource="{Binding GoogleBlogsResults, Mode=TwoWay}" />
As your GoogleBlogsResults property is a
List<Blog>
adding items to it will not trigger the binding engine to fire as the object reference has not changed when you call
NotifyPropertyChanged("GoogleBlogsResults");
You can solve this by following the solution described by T.Ho by using
ObservableCollection<Blog>
which triggers the binding engine automatically when items within the collection are modified or alternatively by generating a new
List<Blog>
object (which merges the new and old items) and setting the GoogleBlogsResults property to the new list.
Hope this helps.
this Tutorial may help you
i think you need to binding source in XAML
DataContext="{Binding Source={StaticResource CustomerContainerObject}}"
or
<ListBox ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"></TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
var employees = new List<Employee>()
{
new Employee { Name = "Scott" },
new Employee { Name = "Poonam"},
new Employee { Name = "Paul" }
};
this.DataContext = employees;
wish that helps.
Instead of implement INotifyProperityChanged interface yourself, you might want to use ObservableCollection<T> instead for your list items. ObservableCollection is a collection class with INotifyProperityChanged implemented, so you don't have to manually call "NotifyPropertyChanged" for the binding to update.
Make sure you have the right DataContext. If you're not using MVVM design pattern, you might want to look into that.

Add Items to ComboBox Programmatically

I have been working with WPF all of 2 days, coming from ASP.NET so bear with me!
I am populating a ComboBox with xml filenames from a directory and adding a icon to each item. I have everything working just fine but I am wondering if there is a "better", more "efficient" way of doing this. As I stated, I am just getting started with WPF and I want to go about things the "right" way. My working code is below, can or should I be going about this a different way? Thanks in advance for any pointers!
<ComboBox Height="24" HorizontalAlignment="Left" Margin="153,138,0,0" Name="cmbFiles" VerticalAlignment="Top" Width="200" //>
private void FillSrFileCombo()
{
string[] dirFiles = Directory.GetFiles(#"D:\TestFiles", "*.xml");
foreach (string datei in dirFiles)
{
string fileName = System.IO.Path.GetFileName(datei);
System.Windows.Controls.StackPanel stkPanel = new StackPanel();
stkPanel.Orientation = Orientation.Horizontal;
cmbFiles.Items.Add(stkPanel);
System.Windows.Controls.Image cboIcon = new Image();
BitmapImage bitMap = new BitmapImage();
bitMap.BeginInit();
bitMap.UriSource = new Uri(#"tag.jpg", UriKind.Relative);
bitMap.EndInit();
cboIcon.Source = bitMap;
cboIcon.Height = 15;
stkPanel.Children.Add(cboIcon);
System.Windows.Controls.TextBlock cboText = new TextBlock();
cboText.Text = " - " + fileName;
stkPanel.Children.Add(cboText);
}
}
I have answered a similar question an hour ago see here :http://stackoverflow.com/questions/9637514/add-usercontrol-to-listbox-wpf.
I will recap the most important parts here based on your example
In the XAML you need to create a "DataTemplate", that is the XAML representation of your file object - in your case an image + file name. You can create this Datatemplate as a resource and assign it to your ComboBox or simply create it in the combobox if you don't plan to reuse it
<ComboBox ItemsSource="{Binding Files}">
<ComboBox.ItemTemplate>
<StackPanel>
<Image Source="{Binding FileImage}" Height="16" Width="16"/>
<TextBlock Margin="5" Text="{Binding FileName}" />
</StackPanel>
</ComboBox.ItemTemplate>
</ComboBox>
In your Codebehind, you need to create a structure that represets the data you want to present in your combobox - let's say a "FileInfo" class. The FileInfo class needs to expose the "FileImage" and "FileName" as properties so you can bind to them (as seen above).
Next, you need to create a collection of such objects in the code-behind of the xaml you put your ComboBox in. The collection needs to be an ObservableCollection.
So you would have smth like this:
public class FileInfo
{
public ImageSource FileImage { get; set; }
public string FileName { get; set; }
}
and then in the MainWindow.xaml.cs
public ObservableCollection Files { get; private set; }
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
Files = new ObservableCollection();
foreach (string datei in dirFiles)
{
var fName = System.IO.Path.GetFileName(datei);
BitmapImage bitMap = new BitmapImage();
bitMap.BeginInit();
bitMap.UriSource = new Uri(#"tag.jpg", UriKind.Relative);
bitMap.EndInit();
Files.Add(new FileInfo(){FileName=fName, FileImage = bitMap});
}
}
You will still need to read a lot about why this will work. I recomend reading about DataTemplates DataBinding, ObservableCollection and in the end, read about MVVM, a pattern that ties all this stuff nicely and allows you to harness all the WPF power and decouple yor logic from the UI.
One way that you should consider for WPF/Silverlight/WP7 apps is the MVVM design pattern.
In this instance you would have a view model containing the collection of items for your ComboBox, and you would use a binding expression to set the ItemsSource of the ComboBox. You would then template the ComboBox to display your item images.
Look into data binding and data templating, the only C# code you should need here is to get the files (even though you could also do that in XAML using something like an ObjectDataProvider)

Categories