I am trying to make some music library app for my classes. I've done pretty much everything i had to but there is one thing left. I don't know how to access data from data template generated item to delete both this item form app and xml node from xml file.
I have found this bit of code that should delete the node i want but i still don't know how to access data from item that i selected.
private void DeleteFromFile_Click(object sender, RoutedEventArgs e)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(#"musicLibrary.xml");
foreach(XmlNode xNode in xDoc.SelectNodes("musicLibrary"))
{
if(xNode.SelectSingleNode("title").InnerText == "")
{
xNode.ParentNode.RemoveChild(xNode);
}
}
}
the nodes looks like this:
<musicLibrary>
<title>I Still Haven't Found What I'm Looking For</title>
<albumName>The Joshua Tree</albumName>
<artist>U2</artist>
<releaseDate>1987</releaseDate>
<tempo>101</tempo>
<duration>4:37</duration>
<genre>Rock</genre>
</musicLibrary>
<musicLibrary>
<title>Magnificent</title>
<albumName>No Line on the Horizon</albumName>
<artist>U2</artist>
<releaseDate>2009</releaseDate>
<tempo>115</tempo>
<duration>5:24</duration>
<genre>Rock</genre>
</musicLibrary>
data templates that i use:
<Page.Resources>
<CollectionViewSource x:Key="listDataView"/>
<DataTemplate x:Key="mDataTamplate">
<StackPanel>
<TextBlock FontSize="12" Margin="5" Text="{Binding title}" />
<TextBlock FontSize="10" Margin="5" Text="{Binding artist}"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="detailedDataTamplate">
<Grid Grid.Row="3" Margin="20,0,20,0">
<!-- Row/Column Definition-->
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.7*"/>
<ColumnDefinition Width="1.5*"/>
<ColumnDefinition Width="0.7*"/>
<ColumnDefinition Width="0.7*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- First Column -->
<TextBlock Grid.Column="0" Grid.Row="0" Text="Title" Style="{StaticResource textBlockStyle}" />
<TextBlock Text="{Binding title}"
Grid.Column="1" Grid.Row="0"
Style="{StaticResource textBlockStyle}"/>
<TextBlock Grid.Column="0" Grid.Row="1" Text="Album name" Style="{StaticResource textBlockStyle}"/>
<TextBlock Text="{Binding albumName}"
Grid.Column="1" Grid.Row="1"
Style="{StaticResource textBlockStyle}"/>
<TextBlock Grid.Column="0" Grid.Row="2" Text="Artist" Style="{StaticResource textBlockStyle}"/>
<TextBlock Text="{Binding artist}"
Grid.Column="1" Grid.Row="2"
Style="{StaticResource textBlockStyle}"/>
<TextBlock Grid.Column="0" Grid.Row="3" Text="Release Date" Style="{StaticResource textBlockStyle}"/>
<TextBlock Text="{Binding releaseDate}"
Grid.Column="1" Grid.Row="3"
Style="{StaticResource textBlockStyle}"/>
<!-- Second Column -->
<TextBlock Grid.Column="2" Grid.Row="0" Text="Tempo" Style="{StaticResource textBlockStyle}" />
<TextBlock Text="{Binding tempo}"
Grid.Column="3" Grid.Row="0"
Style="{StaticResource textBlockStyle}"/>
<TextBlock Grid.Column="2" Grid.Row="1" Text="Duration" Style="{StaticResource textBlockStyle}"/>
<TextBlock Grid.Column="3" Grid.Row="1"
Text="{Binding duration}"
Style="{StaticResource textBlockStyle}"/>
<TextBlock Grid.Column="2" Grid.Row="2" Text="Genre" Style="{StaticResource textBlockStyle}"/>
<TextBlock Grid.Column="3" Grid.Row="2"
Text="{Binding genre}"
Style="{StaticResource textBlockStyle}"/>
<Button x:Name="saveToFile" Click="saveToFile_Click" Content="Save to file" Grid.Column="2" Grid.Row="3" Grid.ColumnSpan="1" VerticalAlignment="Center" Height="31"/>
<Button x:Name="deleteFromFile" Click="DeleteFromFile_Click" Content="Delete" Grid.Column="3" Grid.Row="3"/>
</Grid>
</DataTemplate>
</Page.Resources>
And class that i bind data from:
namespace MLUI
{
[XmlRoot("dataSet")]
public class DataSet
{
[XmlElement("musicLibrary")]
public List<Song> Songs { get; set; }
}
public class Song
{
[XmlElement("title")]
public string title { get; set; }
[XmlElement("artist")]
public string artist { get; set; }
[XmlElement("albumName")]
public string albumName { get; set; }
[XmlElement("releaseDate")]
public string releaseDate { get; set; }
[XmlElement("tempo")]
public int tempo { get; set; }
[XmlElement("duration")]
public string duration { get; set; }
[XmlElement("genre")]
public string genre { get; set; }
public override string ToString()
{
return "Title: " + title +"\r\nArtist: "+ artist +"\r\nAlbum Name: "+ albumName + "\r\nRelease Date: " + releaseDate +
"\r\nTempo "+ tempo + "\r\nDuration " + duration + "\r\nGenre " + genre ;
}
}
}
I like using Xml Linq with a dictionary :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement dataSet = doc.Root;
Dictionary<string, XElement> dictionary = dataSet.Elements("musicLibrary")
.GroupBy(x => (string)x.Element("title"))
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
XElement Magnificent = dictionary["Magnificent"];
Magnificent.Remove();
}
}
}
Related
this is my class TaskTodo and the method GetTask this method connect with sqlite and return a observable collection
using Microsoft.Data.Sqlite;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using Windows.Storage;
namespace uwp_to_do_list
{
public class TaskTodo : INotifyPropertyChanged
{
public string NameTask { get; set; }
public DateTime Reminder { get; set; }
public string NameList { get; set; }
public DateTime Date { get; set; }
public string SubTask { get; set; }
public string Priority { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public ObservableCollection<TaskTodo> GetTasks()
{
var Tasks = new ObservableCollection<TaskTodo>();
//get data from sqlite3
string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "TasksSqlite.db");
using (SqliteConnection db =
new SqliteConnection($"Filename={dbpath}"))
{
db.Open();
SqliteCommand selectCommand = new SqliteCommand
("SELECT Name_task from Task", db);
SqliteDataReader query = selectCommand.ExecuteReader();
while (query.Read())
{
TaskTodo taskTodo = new TaskTodo();
taskTodo.NameTask = query.GetString(0);
Tasks.Add(taskTodo);
}
db.Close();
}
return Tasks;
}
so i put this observable collection as the itemsource of listview, but this just show the type of the object not the field NameTask.
public MainView()
{
this.InitializeComponent();
TaskTodo taskTodo = new TaskTodo();
task_list.ItemsSource = taskTodo.GetTasks()
Debug.WriteLine(taskTodo.GetTasks()[4].NameTask);
}
i think the problem is in the xaml code because went i tested if the observable collection is empty
Debug.WriteLine(taskTodo.GetTasks()[4].NameTask);
the outpuy was tasxk3
my xaml code
<Page
x:Class="uwp_to_do_list.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:uwp_to_do_list"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-
compatibility/2006" xmlns:fa="using:FontAwesome.UWP"
mc:Ignorable="d"
Background="#08090A"
>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"></ColumnDefinition>
<ColumnDefinition Width="auto"></ColumnDefinition>
<ColumnDefinition Width="auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
</Grid.RowDefinitions>
<StackPanel Background="#04000E" Width="240"
Grid.Column="0"
Grid.Row="0" HorizontalAlignment="Left" >
<TextBlock Text="today" Foreground="White" FontSize="24"
HorizontalAlignment="Center" Margin="0,50,0,0">
</TextBlock>
<fa:FontAwesome Icon="CalendarCheckOutline" Height="40"
Width="40" FontSize="40" Foreground="Fuchsia"
HorizontalAlignment="Left" Margin="20,-35,0,0">
</fa:FontAwesome>
<TextBlock Text="Tomorrow" Foreground="White"
FontSize="24" HorizontalAlignment="Center"
Margin="0,20,0,0"></TextBlock>
<fa:FontAwesome Icon="CalendarOutline" Height="40"
Width="40" FontSize="40" Foreground="Fuchsia"
HorizontalAlignment="Left" Margin="20,-35,0,0">
</fa:FontAwesome>
<TextBlock Text="planning" Foreground="White"
FontSize="24" HorizontalAlignment="Center"
Margin="0,20,0,0"></TextBlock>
<fa:FontAwesome Icon="Calendar" Height="40" Width="40"
FontSize="40" Foreground="Fuchsia"
HorizontalAlignment="Left" Margin="20,-35,0,0">
</fa:FontAwesome>
<TextBlock Text="tasks" Foreground="White" FontSize="24"
HorizontalAlignment="Center" Margin="0,20,0,0">
</TextBlock>
<fa:FontAwesome Icon="Home" Height="40" Width="40"
FontSize="40" Foreground="Fuchsia"
HorizontalAlignment="Left" Margin="20,-35,0,0">
</fa:FontAwesome>
</StackPanel>
<TextBox Grid.Row="1" HorizontalAlignment="Left"
Grid.Column="0" Text="+ add a list " Background="#04000E"
Foreground="White" Height="50" Width="240" ></TextBox>
<TextBox x:Name="add_Task_textbox" Grid.Row="1"
Grid.Column="1" KeyDown="add_Task_textbox_KeyDown"
HorizontalAlignment="Center" VerticalAlignment="Center"
Text="+ add a task" Background="#04000E" Foreground="White"
Height="40" Width="1000" Margin="20,0,-20,0" />
<ListView x:Name="task_list" Grid.Row="0" Grid.Column="1"
Background="Transparent">
<ListViewItem>
<DataTemplate x:DataType="local:TaskTodo">
<TextBlock Width="100" Foreground="White" Text="{x:Bind
NameTask}"></TextBlock>
</DataTemplate>
</ListViewItem>
</ListView>
</Grid>
</Page>
for more context my github repository
You should set the ItemTemplate property to your DataTemplate instead of adding a ListViewItem:
<ListView x:Name="task_list" Grid.Row="0" Grid.Column="1"
Background="Transparent">
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:TaskTodo">
<TextBlock Width="100" Foreground="White"
Text="{x:Bind NameTask}" />
</DataTemplate>
<ListView.ItemTemplate>
</ListView>
I have WPF project "LittleLibrary" and and it must enable adding and deleting books. So in Xaml i have form and one button
Here is how it looks like https://imgur.com/1N7PYWm
and in C# code i'm trying to serialization like this (I'm using Newtonsoft.Json)
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public string Genre { get; set; }
public int Year { get; set; }
public string Cover { get; set; }
public int Availability { get; set; }
public string Description { get; set; }
}
public class RootObject
{
public List<Book> Book { get; set; }
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
RootObject rootObjectSerializacja = new RootObject();
Book newBook = new Book();
newBook.Title = titleTextBox.Text;
newBook.Author = authorTextBox.Text;
newBook.Genre = gatunekTextBox.Text;
newBook.Year = int.Parse(rokWydaniaTextBox.Text);
newBook.Cover = okladkaTextBox.Text;
newBook.Availability = int.Parse(dostepnoscTextBox.Text);
newBook.Description = opisTextBox.Text;
rootObjectSerializacja.Book.Add(newBook);
string content = JsonConvert.SerializeObject(rootObjectSerializacja);
File.WriteAllText("newJsonFile.json", content);
}
Code from my Xaml :
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MinWidth="200"></ColumnDefinition>
<ColumnDefinition Width="*" MinWidth="300"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="7*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<!--Lewa strona -->
<Label x:Name="titleLabel" Grid.Column="0" Grid.Row="0" HorizontalAlignment="Right" VerticalAlignment="Center">Title:</Label>
<TextBox x:Name="titleTextBox" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" Width="150"></TextBox>
<Label x:Name="authorLabel" Grid.Column="0" Grid.Row="1" HorizontalAlignment="Right" VerticalAlignment="Center">Author:</Label>
<TextBox x:Name="authorTextBox" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" Width="150"></TextBox>
<Label x:Name="gatunekLabel" Grid.Column="0" Grid.Row="2" HorizontalAlignment="Right" VerticalAlignment="Center">Gentre:</Label>
<TextBox x:Name="gatunekTextBox" Grid.Column="1" Grid.Row="2" Width="150" HorizontalAlignment="Center" VerticalAlignment="Center" ></TextBox>
<Label x:Name="rokLabel" Grid.Column="0" Grid.Row="3" HorizontalAlignment="Right" VerticalAlignment="Center">Year:</Label>
<TextBox x:Name="rokWydaniaTextBox" Grid.Column="1" Grid.Row="3" Width="150" HorizontalAlignment="Center" VerticalAlignment="Center" ></TextBox>
<Label x:Name="okladkaLabel" Grid.Column="0" Grid.Row="4" HorizontalAlignment="Right" VerticalAlignment="Center">Cover:</Label>
<TextBox x:Name="okladkaTextBox" Grid.Column="1" Grid.Row="4" Width="150" HorizontalAlignment="Center" VerticalAlignment="Center" ></TextBox>
<Label x:Name="dostepnoscLabel" Grid.Column="0" Grid.Row="5" HorizontalAlignment="Right" VerticalAlignment="Center">Avb:</Label>
<TextBox x:Name="dostepnoscTextBox" Grid.Column="1" Grid.Row="5" Width="150" HorizontalAlignment="Center" VerticalAlignment="Center" ></TextBox>
<Label x:Name="opisLabel" Grid.Column="0" Grid.Row="6" HorizontalAlignment="Right" VerticalAlignment="Center">Description:</Label>
<TextBox x:Name="opisTextBox" Grid.Column="1" Grid.Row="6" Width="150" ></TextBox>
</Grid>
<Button x:Name="btnAdd" Grid.Column="0" Grid.Row="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="150" Margin="10" Click="btnAdd_Click" >ADD</Button>
</Grid>
</Grid>
The problem is i have an
Exception {"The object reference has not been set to the instance of the object."} System.NullReferenceException
And content is NULL. What i'm doing wrong ?
Try adding a constructor in your RootObject class.
public class RootObject
{
public List<Book> Book { get; set; }
public RootObject()
{
Book = new List<string>();
}
}
I am using the folloowing class but its not allowing me to display show_times in my xaml its just comming up
popcornpk.datamodel.fetchtiming
public class FetchTiming
{
public string id { get; set; }
public string theater_name { get; set; }
public string address { get; set; }
public List<string> show_times { get; set; }
public string screen_id { get; set; }
public string title { get; set; }
}
public class MovieDetail
{
public MovieDetails movie_details { get; set; }
public List<FetchTiming> fetch_timing { get; set; }
}
My Class call
public async Task<MovieDetail> GetMovieShowtimesAsync()
{
string jsonresult = await WCFRESTServiceCall("GET", "movie_details");
var jarray = JsonConvert.DeserializeObject<MovieDetail>(jsonresult);
return jarray;
}
This is my xamlmethod call I hav eno idea what is going on the data is being returned ok but I just cant seem to dispaly it
private async void listViewShowtimes_Loaded(object sender, RoutedEventArgs e)
{
popcornpk_Dal _dal = new popcornpk_Dal();
MovieDetail _showTimes = await _dal.GetMovieShowtimesAsync();
var listView = (ListView)sender;
listView.ItemsSource = _showTimes.fetch_timing.ToList();
}
Xaml Of DataTemplate
<PivotItem x:Name="pvtShowTimes" Header="showtimes">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ListView x:Name="listViewShowtimes" ItemsSource="{Binding}" Loaded="listViewShowtimes_Loaded">
<DataTemplate>
<StackPanel Height="505">
<TextBlock FontSize="13" x:Name="txtshowtime" Text="{Binding theater_name}" HorizontalAlignment="Left" Margin="19,223,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="212" Foreground="White" Height="29" SelectionChanged="txtTtile_SelectionChanged"/>
<TextBlock FontSize="13" x:Name="txtshow_times" Text="{Binding address}" HorizontalAlignment="Left" Margin="19,223,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="212" Foreground="White" Height="29" SelectionChanged="txtTtile_SelectionChanged"/>
</StackPanel>
</DataTemplate>
</ListView>
</Grid>
</PivotItem>
Below is a screen shot of the app running on the device any help be greatly apreciated.
Ok So i have it at least displaying the thertre name which is good on the show times screen but its still not allowing me to display the show_times field.
<ListView x:Name="listViewShowtimes" ItemsSource="{Binding}" Loaded="listViewShowtimes_Loaded">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Grid.Row="0">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock FontSize="13" Grid.Row="0" Grid.Column="0" x:Name="txtshowtime" Text="{Binding theater_name}" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Width="212" Foreground="White" Height="29" />
<TextBlock FontSize="13" Grid.Row="1" Grid.Column="0" x:Name="txtshow_times" Text="{Binding show_times}" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Width="212" Foreground="White" Height="29" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
I think what i need to no is how to bind a list of strings through xaml Problem I have i need the show times to appear below the cinema name you see their
You have Text="{Binding show_times}" so In your class FetchTiming,
public List<string> show_times { get; set; }
is a list so if you bind it to a TextBlock, it will simply do ToString(). You have to add inside the template another ListView like:
<TextBlock FontSize="13" Grid.Row="0" Grid.Column="0" x:Name="txtshowtime" Text="{Binding theater_name}" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Width="212" Foreground="White" Height="29" />
<ListView ItemsSource={Binding show_times} />
And will do the trick.
I have ListBox in xaml:
<ListBox Name="feedListBox" Height="758" HorizontalAlignment="Center" Margin="0,10,0,0" VerticalAlignment="Top" Width="480" ScrollViewer.VerticalScrollBarVisibility="Auto" SelectionChanged="feedListBox_SelectionChanged" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="1" Background="White">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel VerticalAlignment="Top" Width="480">
<TextBlock FontWeight="Bold" FontSize="24" Name="feedTitle" TextWrapping="Wrap" Margin="12,0,0,0" HorizontalAlignment="Left" Foreground="#FF000000" Text="{Binding Title.Text, Converter={StaticResource RssTextTrimmer}}" />
<TextBlock Name="feedSummary" Foreground="#FF000000" TextWrapping="Wrap" Margin="12,0,0,0" Text="{Binding Summary.Text, Converter={StaticResource RssTextTrimmer}}" />
<TextBlock Name="feedPubDate" Foreground="#FF939393" Margin="12,0,10,10" Text="{Binding PublishDate.DateTime}" HorizontalAlignment="Right" />
<Border BorderThickness="1" Height="2" HorizontalAlignment="Center" VerticalAlignment="Top" Width="480" BorderBrush="Black" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
How can I specify different background for each item?
add a Brush property to your viewmodel and bind the controls in your DataTemplate to it
ViewModel:
using System.ComponentModel;
using System.Windows.Media;
...
public class YourViewModel : INotifyPropertyChanged{
...
private Brush _backgroundCol = Brushes.Red; //Default color
public Brush BackgroundCol
{
get { return _backgroundCol; }
set
{
_backgroundCol = value;
OnPropertyChanged("BackgroundCol");
}
}
...
}
xaml:
<TextBlock Name="feedPubDate" Background="{Binding Path=BackgroundCol}" />
for Information about how to implement the INotifyPropertyChanged interface have a look at: Implementing INotifyPropertyChanged - does a better way exist?
Try this:
XAML:
<ListBox Name="feedListBox" Height="758" HorizontalAlignment="Center" Margin="0,10,0,0" VerticalAlignment="Top" Width="480" ScrollViewer.VerticalScrollBarVisibility="Auto" SelectionChanged="feedListBox_SelectionChanged" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="1" Background="White">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel VerticalAlignment="Top" Width="480">
<Grid Background="{Binding feedTitleBack}">
<TextBlock FontWeight="Bold" FontSize="24" Name="feedTitle" TextWrapping="Wrap" Margin="12,0,0,0" HorizontalAlignment="Left" Foreground="#FF000000" Text="{Binding Title}"/>
</Grid>
<Grid Background="{Binding feedSummaryBack}">
<TextBlock Name="feedSummary" Foreground="#FF000000" TextWrapping="Wrap" Margin="12,0,0,0" Text="{Binding Summary}" />
</Grid>
<Grid Background="{Binding feedPubDateBack}">
<TextBlock Name="feedPubDate" Foreground="#FF939393" Margin="12,0,10,10" Text="{Binding PublishDate}" HorizontalAlignment="Right" />
</Grid>
<Border BorderThickness="1" Height="2" HorizontalAlignment="Center" VerticalAlignment="Top" Width="480" BorderBrush="Black" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
CS:
public class data
{
public string Title { get; set; }
public string feedTitleBack { get; set; }
public string Summary { get; set; }
public string feedSummaryBack { get; set; }
public string PublishDate { get; set; }
public string feedPubDateBack { get; set; }
public data() { }
public data(string Title, string feedTitleBack, string Summary, string feedSummaryBack, string PublishDate, string feedPubDateBack)
{
this.Title = Title;
this.feedTitleBack = feedTitleBack;
this.Summary = Summary;
this.feedSummaryBack = feedSummaryBack;
this.PublishDate = PublishDate;
this.feedPubDateBack = feedPubDateBack;
}
}
void loadData()
{
List<data> obj = new List<data>();
obj.Add(new data("Title1", "Red", "Summary1", "Green", "Date", "Blue"));
obj.Add(new data("Title1", "#DD4B39", "Summary1", "#006621", "Date", "#1A0DAB"));
feedListBox.ItemsSource = obj;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
loadData();
}
I would like to set in Silverlight for each item in a ListBox a tooltip with many rows.
In XAML i have a listbox and a button:
<ListBox Height="100" HorizontalAlignment="Left" Margin="24,136,0,0" Name="listBox1" VerticalAlignment="Top" Width="109" ItemsSource="{Binding}">
<Button Content="Add" Name="button_add" VerticalAlignment="Top" Width="118" Click="add_Click">
in c#
private void button_add_Click(object sender, RoutedEventArgs e)
{
ObservableCollection<Person> obs1 = new ObservableCollection<Person>();
obs1.Add(new Person(){Name="Name1", Age=1});
obs1.Add(new Person(){Name="Name2", Age=2});
listBox1.ItemsSource = obs1;
// This Line of Code MUST NOT BE USED!! listBox1.DisplayMemberPath = "Name";
}
public class Person
{
public String Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return Name;
}
}
I would like to show for each item the Age as my tooltip.
Edit: Ok, this is the Solution for showing only AGE as tooltip. That is one Line/Row.
<ListBox Height="100" HorizontalAlignment="Left" Margin="24,136,0,0" Name="listBox1" VerticalAlignment="Top" Width="109" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" ToolTipService.ToolTip="{Binding Age}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
But what if i want to show a Tooltip with 2 Lines? something like:
Name: Name1
Age: 1
Edit: 3 rows, 2 columns. i also added public String Comment { set; get; } to class Person
<ListBox Height="100" HorizontalAlignment="Left" Margin="24,136,0,0" Name="listBox1" VerticalAlignment="Top" Width="109" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<ToolTipService.ToolTip>
<ToolTip>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition Height="40"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80"/>
<ColumnDefinition Width="250"/>
</Grid.ColumnDefinitions>
<TextBlock Text="Name: " Grid.Row="0" Grid.Column="0" />
<TextBlock Text="{Binding Name}" Grid.Row="0" Grid.Column="1"/>
<TextBlock Text="Age: " Grid.Row="1" Grid.Column="0"/>
<TextBlock Text="{Binding Age}" Grid.Row="1" Grid.Column="1"/>
<TextBlock Text="Comment: " Grid.Row="2" Grid.Column="0"/>
<TextBlock Text="{Binding Comment}" Grid.Row="2" Grid.Column="1" TextWrapping="Wrap" />
</Grid>
</ToolTip>
</ToolTipService.ToolTip>
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
But there is stil a problem. The comment can be short or long, so i would like to make the ROWS/LINES/SPACE for Comment to be variable or else Text is cut off.
You can use any controls for tooltip content:
<ToolTipService.ToolTip>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Name}" />
<TextBlock Text="{Binding Age}" />
</StackPanel>
</ToolTipService.ToolTip>
Other possibility would be to use a converter, that returns the Name and Age separated by \r\n.