C# Passing StringBuilder in a ListboxItems Content - c#

I have a listbox in which i pass in every row 5 items. My XML file looks like this :
<ListBox x:Name="DatabaseBox" ItemsSource="{Binding Book}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Width="auto" Height="22">
<Image x:Name="ToggleFavoriteImage" Width="10" Height="10" Tag="{Binding Tag}" Source="{Binding ImageSource}" HorizontalAlignment="Center"/>
<TextBlock Text="{Binding Name}" HorizontalAlignment="Left" Margin="10,0,0,0" VerticalAlignment="Center"/>
<ListBoxItem Content="{Binding City}" HorizontalAlignment="Center"/>
<ListBoxItem Content="{Binding Author}" HorizontalAlignment="Center"/>
<ListBoxItem Content="{Binding Country}" HorizontalAlignment="Center"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Where Book is a private static List<BookItems> Book{ get; set; } and BookItems is
public struct BookItems
{
public string Name{ get; set; }
public string Url { get; set; }
public string Author{ get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Tag { get; set; }
public ImageSource ImageSource { get; set; }
}
All my data that i want to pass in ListBox are stored in another List :private static List<Tuple<StringBuilder , StringBuilder , StringBuilder , StringBuilder , StringBuilder >> BookList = new List<Tuple<StringBuilder , StringBuilder , StringBuilder , StringBuilder , StringBuilder >>();
So if i try to fill my ListBox that way :
foreach(var ListItem in BookList)
{
Book= new List<BookItems>()
{
new BookItems()
{
Tag = ListItem.Item1.ToString(),ImageSource = FavoriteSource, Name= ListItem.Item1.ToString(), Author= ListItem.Item3.ToString(), City = ListItem.Item4.ToString(),Country = ListItem.Item5.ToString()
}
};
DatabaseBox.Items.Add(Book);
}
then i get everywhere null except the image. If i change my BookList to strings and my Book also, then everything goes smooth without any problems. I check every time the convertions from StringBuilder to string with a Console outpout and my strings are null, where my StringBuilder is ok. Am i doing something so wrong?

You should create instances for StringBuilder items in tuple like new StringBuilder()

as you said, the stringBuilder is just fine so my solution to you is first of all do not create a list for every item. i don't know why are you doing it but there shouldn't be a list for every item you add to DatabaseBox.
second, take your code
Book= new List<BookItems>()
{
new BookItems()
{
Tag = ListItem.Item1.ToString(),ImageSource = FavoriteSource, Name= ListItem.Item1.ToString(), Author= ListItem.Item3.ToString(), City = ListItem.Item4.ToString(),Country = ListItem.Item5.ToString()
}
};
and rewrite it. also rewrite the properties in BookItems and make it a class.
after you do all of that the debug process will be easy. if the stringBuilders contains the data you will see exactly what happens to it.

Related

How to Bind an Observablecollection to a GridView?

I am working on an App that selects Images and adds them to an Observablecollection. I want to show this collection in Xaml. There is no clear understandable answer that I have found so far.
in the MainPage:
public ObservableCollection<TimerWallpaper> timerWallpapers = new ObservableCollection<TimerWallpaper>();
And then the code for its class is this:
public class TimerWallpaper
{
public string timerFileName;
public BitmapImage timerImgSource;
public string timerTime;
public TimerWallpaper(string name, BitmapImage imgSource, int hours, int mins)
{
this.timerFileName = name;
this.timerImgSource = imgSource;
this.timerTime = hours.ToString() + " : " + mins.ToString();
}
}
Till this point it seems as the code is working.. the obstacle is with this code:
<GridView ItemsSource="x:Bind timerWallpapers">
<GridView.ItemTemplate>
<DataTemplate x:DataType="local:TimerWallpaper">
<Image Height="100" Width="100" Source="x:Bind timerImgSource"/>
<TextBlock Text="{x:Bind timerFileName}"/>
<TextBlock Text="{x:Bind timerTime}"/>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
I keep getting "Invalid Value" for the elements of the data templet.
What are the requirements to bind the GridView to the collection?
What is the correct format to do so?
OK, there are a number of problems with your code. First off, you should bind to properties, not fields, so your MainPage.cs should look something like this:
public sealed partial class MainPage : Page
{
public ObservableCollection<TimerWallpaper> TimerWallpapers { get; set; }
public MainPage()
{
this.InitializeComponent();
TimerWallpapers = new ObservableCollection<TimerWallpaper>();
DataContext = this;
}
}
and your TimerWallpaper like this:
public class TimerWallpaper
{
public string TimerFileName { get; set; }
public BitmapImage TimerImgSource { get; set; }
public string TimerTime { get; set; }
public TimerWallpaper(string name, BitmapImage imgSource, int hours, int mins)
{
this.TimerFileName = name;
this.TimerImgSource = imgSource;
this.TimerTime = hours.ToString() + " : " + mins.ToString();
}
}
(Or use private set if you want to)
Next, your binding syntax is wrong on a couple of lines where you forgot to enclose it in curly braces, and lastly, the DataTemplate can only have a single child, so you need to wrap your UI elements in a layout, e.g. a StackPanel, like so:
<GridView ItemsSource="{x:Bind TimerWallpapers}">
<GridView.ItemTemplate>
<DataTemplate x:DataType="local:TimerWallpaper">
<StackPanel>
<Image Height="100" Width="100" Source="{x:Bind TimerImgSource}"/>
<TextBlock Text="{x:Bind TimerFileName}"/>
<TextBlock Text="{x:Bind TimerTime}"/>
</StackPanel>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>

How to Bind dynamic values in Xaml using WPF in c#

I have created application in WPF with two window. In one window i have used with one text box and submit button. Once submit from first window i hide first window and show second window. I have taken some values using first window text value and need to bind in second window Xaml. Actually that values can bind using foreach in html(mvc) but need to bind Xaml for display in second window. Please give some suggestions.
Please find the below answer, It will work definitely
Xaml :
<ItemsControl Name="icTodoList">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="200,50,0,30">
<TextBlock>
<Hyperlink TextDecorations="None" NavigateUri="{Binding UriPath}" RequestNavigate="Hyperlink_RequestNavigate"
CommandParameter="{Binding ElementName=myImg}">
<Image HorizontalAlignment="Left" Width="80" Height="80" x:Name="myImg" Source="{Binding Source}" Margin="5"/>
</Hyperlink>
</TextBlock>
<TextBlock TextAlignment="Left" Margin="200,30,0,0">
<TextBlock FontSize="22px" Text="{Binding Title}" Foreground="white"></TextBlock>
</TextBlock>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
C# code for binding Values,
public class DMScreen3 {
public List<string> AllFiles { get; set; }
List<BindingFilesContent> items = new List<BindingFilesContent>();
if(AllFiles != null)
{
foreach(var r in AllFiles)
{
if ((r.ToLower().Contains(".avi") || r.ToLower().Contains(".mp4")) && fileTypes == "video")
{
items.Add(new BindingFilesContent() { Title = Path.GetFileName(r), UriPath = r, Source = "/images/videoicon.png" });
}
icTodoList.ItemsSource = items;
}
}
}
public class BindingFilesContent
{
public string Title { get; set; }
public string Source { get; set; }
public string UriPath { get; set; }
}

binding events to wpf list for realtime update

I am building a WPF app that will populate filtered headlines from a variety of news services. Each headline triggers an event, which in a console app I can display on the console. I want to use WPF here but have bot used it prior to this endeavor. My mainwindow xaml is as shown below. My original thought was to have an ObservableCollection populate list items in a listview in the xaml. If that is not the right approach, I'm open to expert opinion on a better way as speed of receipt to display is vital. If what I am doing is proper then how do I bind a new entry to the ObservableCollection to a new list item to display?
<StackPanel Orientation="Vertical" Margin="5,150 5 50" Name="HeadlinePanel">
<TextBlock Text="Filtered Headlines From Monitoring List"
HorizontalAlignment="Left" Margin="0,0 5 5" Name="ScrollingHeadlineLabel" FontWeight="Bold" FontSize="14" Background="LightSkyBlue" />
<ListBox>
<ListBoxItem>
<StackPanel Orientation="Horizontal">
<Image Source="a property on the headline" />
<TextBlock><Run Text="headline is from a website"/></TextBlock>
</StackPanel>
</ListBoxItem>
<ListBoxItem>
<StackPanel Orientation="Horizontal">
<Image Source="a property on the headline" />
<TextBlock><Run Text="headline is from TWTR"/></TextBlock>
</StackPanel>
</ListBoxItem>
<ListBoxItem>
<StackPanel Orientation="Horizontal">
<Image Source="a property on the headline" />
<TextBlock><Run Text="headline from a different website"/></TextBlock>
</StackPanel>
</ListBoxItem>
<ListBoxItem>
<StackPanel Orientation="Horizontal">
<Image Source="a property on the headline" />
<TextBlock><Run Text="text from a different tweet"/></TextBlock>
</StackPanel>
</ListBoxItem>
</ListBox>
</StackPanel>
In the console app the streaming begins (code shown below) in the filteredStream.Start() but the handler needs to register prior. In the console app I can write to the console (commented out) but here I add the headline object to the collection when the event fires. My question is how to bind that to my xaml list items. I will initiate the stream from mainwindow method? or some method I create to run within that?
var config = new TwitterOAuthConfig()
{
ConsumerKey = customerKey,
ConsumerSecret = customerSecret,
AccessToken = accessToken,
AccessTokenSecret = accessTokenSecret,
GeoOnly = false,
KeywordsToMonitor = keywords,
UsersToFollow = followers
};
var filteredStream = new TwitterClient(config);
var headlineCollection = new ObservableCollection<Headline>();
// subscribe to the event handler
filteredStream.HeadlineReceivedEvent +=
(sender, arguments) => headlineCollection.Add(arguments.Headline);
//Console.WriteLine("ID: {0} said {1}", arguments.Headline.Username, arguments.Headline.HeadlineText);
filteredStream.ExceptionReceived += (sender, exception) => Console.WriteLine(exception.HeadlineException.ResponseMessage);
filteredStream.Start();
Here is my Original HeadlineViewModel
public class HeadlineViewModel : ObservableItem
{
private string _headlineText;
public string Source { get; set; }
public string Username { get; set; }
public string Text
{
get { return _headlineText; }
set
{
_headlineText = value;
RaisePropertyChangedEvent("HeadlineText");
}
}
public List<string> UrlsParsedFromText { get; set; }
public string TimeStamp { get; set; }
}
I've updated it to the following:
public class HeadlineViewModel
{
public class HeadlineDisplayItems: ObservableItem
{
private string _headlineText;
public string HeadlineIconPath { get; set; }
public string TimeStamp { get; set; }
public string Username { get; set; }
public string Text
{
get { return _headlineText; }
set
{
_headlineText = value;
RaisePropertyChangedEvent("HeadlineText");
}
}
}
public List<string> UrlsParsedFromText { get; set; }
public ObservableCollection<HeadlineDisplayItems> HeadlineCollection { get; set; }
}
I don't know about your architecture, but wpf is mostly used with what they call MVVM (Model-View-ViewModel) where you have your View (you already posted the code), the ViewModel (I believe you don't have one) and the model (that is the Headline you are using). The objective of the ViewModel is to simplify the life of the view and make available all the information and actions it needs to display.
For example, you should hava a ViewModel for the whole view you are building, let's say "HeadlinePanelViewModel" (I don't recommend panel in the name because the idea of using a ViewModel is to abstract the controls or technologies being used). The HeadlinePanelViewModel needs to make the headlines available, so it must have a collection of a ViewModel representing all the information concerned to the headline (icons, titles, links, ...). In the end, you have an HeadlinePanelViewModel which contains an ObservableCollection. Set this as DataContext of your View and you must be ready to go to display your info.
Now comes the part of actually loading the info. Again, I don't know about your architecture. But in VERY simple terms, you could instantiate the filteredStream inside of your HeadlinePanelViewModel and everytime an HeadlineReceivedEvent is fired, you create an HeadlineViewModel corresponding to it and add to your collection.
"Complete" code based in the code in your answer:
The ViewModel:
public class HeadlineViewModel
{
public HeadlineViewModel()
{
// This is here only for simplicity. Put elsewhere
var config = new TwitterOAuthConfig()
{
ConsumerKey = customerKey,
ConsumerSecret = customerSecret,
AccessToken = accessToken,
AccessTokenSecret = accessTokenSecret,
GeoOnly = false,
KeywordsToMonitor = keywords,
UsersToFollow = followers
};
var filteredStream = new TwitterClient(config);
HeadlineCollection = new ObservableCollection<HeadlineDisplayItems>();
// subscribe to the event handler
filteredStream.HeadlineReceivedEvent +=
(sender, arguments) => HeadlineCollection.Add(ConvertToViewModel(arguments.Headline));
//Console.WriteLine("ID: {0} said {1}", arguments.Headline.Username, arguments.Headline.HeadlineText);
filteredStream.ExceptionReceived += (sender, exception) => Console.WriteLine(exception.HeadlineException.ResponseMessage);
filteredStream.Start();
}
private HeadlineDisplayItems ConvertToViewModel(Headline headline)
{
// Conversion code here
}
public class HeadlineDisplayItems: ObservableItem
{
private string _headlineText;
public string HeadlineIconPath { get; set; }
public string TimeStamp { get; set; }
public string Username { get; set; }
public string Text
{
get { return _headlineText; }
set
{
_headlineText = value;
RaisePropertyChangedEvent("HeadlineText");
}
}
}
public List<string> UrlsParsedFromText { get; set; }
public ObservableCollection<HeadlineDisplayItems> HeadlineCollection { get; set; }
}
The View:
<StackPanel Orientation="Vertical" Margin="5,150 5 50" Name="HeadlinePanel">
<TextBlock Text="Filtered Headlines From Monitoring List"
HorizontalAlignment="Left" Margin="0,0 5 5" Name="ScrollingHeadlineLabel" FontWeight="Bold" FontSize="14" Background="LightSkyBlue" />
<ListBox ItemsSource="{Binding HeadlineCollection}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding HeadlineIconPath}" />
<TextBlock><Run Text="{Binding Text}"/></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
The code missing is where you do the this.DataContext = new HeadlineViewModel(); to the View.
EDIT: You may experience some problems with cross-thread operations if you try to update the observableCollection from a thread different of the view thread. A workaround is to use the solution in this link, but I don't think it's the best approach.
Create your ObservableCollection as a Property that you can Reference in XAML. Either create it directly in your MainWindow-Class or instantiate your collection as a StaticResource.
Bind your ObservableCollection as ItemsSource to your Listbox
<ListBox ItemsSource="{Binding Path=HeadlineCollection}"></ListBox>
and use an DataTemplate to bind your data to it
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image ... />
<TextBlock Text="{Binding Path=Text}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
For the Headline, create a data class that manages what you need to display (headline, icons, etc.). Something like this:
class Headline
{
bool isTwitter {get; set;}
string Text {get; set;}
}
Then in your client object you can simply add a new object to the ObservableCollection by calling the Add()-Method and the Application will automatically render the new object.
You can start your query client on the main UI thread but for a responsive UI you should let the query routine run in it's own thread (e.g. by using a BackgroundWorker) so that the UI isn't cluttered by it.

how to display an image from web service

I am building my first app in windows phone 7. I need to show data from web service along with an image. I am able to show the data but not able to show the image.
My xaml code is:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox Name="listBox1">
<ListBox.ItemTemplate>
<DataTemplate>
<Button>
<Button.Content>
<ScrollViewer HorizontalScrollBarVisibility="Auto" Height="80" Width="400">
<!--<ScrollViewer Height="80">-->
<StackPanel Orientation="Horizontal" Margin="0,0,0,0">
<StackPanel Orientation="Vertical" Height="80">
<TextBlock Text="{Binding Path=News_Title}" TextWrapping="Wrap" ></TextBlock>
<TextBlock Text="{Binding Path=News_Description}" TextWrapping="Wrap"></TextBlock>
<TextBlock Text="{Binding Path=Date_Start}" TextWrapping="Wrap"></TextBlock>
<Image Source="{Binding Path=Image_Path}" />
</StackPanel>
</StackPanel>
</ScrollViewer>
</Button.Content>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
The .cs code is:
public class Newss
{
public string News_Title { get; set; }
public string News_Description { get; set; }
public string Date_Start { get; set; }
}
public News()
{
InitializeComponent();
KejriwalService.aapSoapClient client = new KejriwalService.aapSoapClient();
client.getarvindNewsCompleted += new EventHandler<KejriwalService.getarvindNewsCompletedEventArgs>(client_getarvindNewsCompleted);
client.getarvindNewsAsync();
}
void client_getarvindNewsCompleted(object sender, KejriwalService.getarvindNewsCompletedEventArgs e)
{
string result = e.Result.ToString();
List<Newss> listData = new List<Newss>();
XDocument doc = XDocument.Parse(result);
foreach (var location in doc.Descendants("UserDetails"))
{
Newss data = new Newss();
data.News_Title = location.Element("News_Title").Value;
data.Date_Start = location.Element("Date_Start").Value;
listData.Add(data);
}
listBox1.ItemsSource = listData;
}
}
Xml String:
<NewDataSet>
<UserDetails>
<id>11</id>
<News_Title>Disciplinary Action against Vinod Binny</News_Title>
<News_Description>The Aam Aadmi Party formed a disciplinary committee, on 19-Jan-2013, headed by Pankaj Gupta to look into the matter of Vinod Kumar Binny. The other members of the committee included Ashish Talwar, Illyas Azmi, Yogendra Yadav and Gopal Rai.
This disciplinary committee has decided to expel Vinod Kumar Binny and terminate his primary membership from the party, for publicly making false statements against the party and its leadership, thereby bringing disrepute to the party. A letter to the same end has been issued to Vinod Kumar Binny.</News_Description>
<Date_Start>2014-01-29</Date_Start>
<image_path>news.png</image_path>
Can anyone help me in displaying the images for each field.
The image path is an http url
http://political-leader.vzons.com/ArvindKejriwal/images/uploaded/news.png
If i guess right your Image_Path is a http url . so you need to BitmapImage to bind as a ImageSource. may this will help you.
public class Newss
{
public string News_Title { get; set; }
public string News_Description { get; set; }
public string Date_Start { get; set; }
**//Edits**
public string image_path {get;set}
public BitmapImage ImageBind{get;set;}
}
foreach (var location in doc.Descendants("UserDetails"))
{
Newss data = new Newss();
data.News_Title = location.Element("News_Title").Value;
data.Date_Start = location.Element("Date_Start").Value;
**//Edits**
data.image_path = location.Element("Image_Path").Value;
data.ImageBind = new BitmapImage(new Uri( #"http://political-leader.vzons.com/ArvindKejriwal/images/uploaded/"+data.image_path, UriKind.Absolute)
listData.Add(data);
}
**Your xaml changes**
<Image Source="{Binding ImageBind }" />

How do I display images from back office in windows phone 7 application?

I am building my first app in windows phone 7. I need to show some data from web service along with an image. I am able to show the data but do not know how to display the images. New data can be entered which needs to be updated. The image will come from backoffice and the path will come from web service. My web service is:
<string><NewDataSet>
<UserDetails>
<id>5</id>
<News_Title>Audit of Electricity Companies</News_Title>
<News_Description> Rejecting the contention of private power distributors, the Delhi government today ordered an audit of their finances by the government's national auditor or Comptroller and Auditor General (CAG), fulfilling yet another election promise of the Aam Aadmi Party.
</News_Description>
<Date_Start>2014-01-03</Date_Start>
<image_path>news.png</image_path>
</UserDetails>
There will be more than 1 data. I am able to show news_Title, news_description, Date_start. My cs code is
public class Newss
{
public string News_Title { get; set; }
public string News_Description { get; set; }
public string Date_Start { get; set; }
}
public News()
{
InitializeComponent();
KejriwalService.aapSoapClient client = new KejriwalService.aapSoapClient();
client.getarvindNewsCompleted += new EventHandler<KejriwalService.getarvindNewsCompletedEventArgs>(client_getarvindNewsCompleted);
client.getarvindNewsAsync();
}
void client_getarvindNewsCompleted(object sender, KejriwalService.getarvindNewsCompletedEventArgs e)
{
string result = e.Result.ToString();
List<Newss> listData = new List<Newss>();
XDocument doc = XDocument.Parse(result);
// Just as an example of using the namespace...
//var b = doc.Element("NewDataSet").Value;
foreach (var location in doc.Descendants("UserDetails"))
{
Newss data = new Newss();
data.News_Title = location.Element("News_Title").Value;
// data.News_Description = location.Element("News_Description").Value;
data.Date_Start = location.Element("Date_Start").Value;
listData.Add(data);
}
listBox1.ItemsSource = listData;
}
My xaml file is
<ScrollViewer Margin="12,17,-12,144" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Auto" AllowDrop="False" ManipulationMode="Control">
<ListBox Name="listBox1" Margin="38,86,38,562">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=News_Title}"></TextBlock>
<TextBlock Text="{Binding Path=News_Description}"></TextBlock>
<TextBlock Text="{Binding Path=Date_Start}"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</ScrollViewer>
Add this to your model
public class Newss
{
public string News_Title { get; set; }
public string News_Description { get; set; }
public string Date_Start { get; set; }
public string Image_Path { get; set; }
}
Set the image property in your foreach loop
foreach (var location in doc.Descendants("UserDetails"))
{
Newss data = new Newss();
data.News_Title = location.Element("News_Title").Value;
// data.News_Description = location.Element("News_Description").Value;
data.Date_Start = location.Element("Date_Start").Value;
Newss.Image_Path = location.Element("image_path").Value
listData.Add(data);
}
In your Xaml
<ScrollViewer Margin="12,17,-12,144" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Auto" AllowDrop="False" ManipulationMode="Control">
<ListBox Name="listBox1" Margin="38,86,38,562">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=News_Title}"></TextBlock>
<TextBlock Text="{Binding Path=News_Description}"></TextBlock>
<TextBlock Text="{Binding Path=Date_Start}"></TextBlock>
<Image Source="{Binding Path=Image_Path}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</ScrollViewer>
And obviously, ensure that the Image_Path data from your xml payload is a valid uri, i would start by setting it to a static image such as "http://static.bbci.co.uk/frameworks/barlesque/2.59.4/orb/4/img/bbc-blocks-dark.png"

Categories

Resources