Data binding into textblock from sqlite database on windows store app - c#

I'm trying to bind my data from sqlite.net database into textblock. I've searched a lot about it, but I still have a few problems:
1) anoying exception occurs where in the Additional Information is: "Constraint" and nothing else. The problem is also that it doesn't appear every time I run the app.
2) I cannot see my Binding data into the textblock.
I've composed me code according to this example: Windows Store App writing sqlite query into the listview's textblocks
I've tried also this select data from sqlite database and binding values to listbox item in windows phone 8 apps
but none of this solving my problem.
Here is my XAML code:
<Grid>
<Grid.Background>
<ImageBrush ImageSource="/Assets/rankingTlo.png"/>
</Grid.Background>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="5*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="4*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Column="1" HorizontalAlignment="Center" Text="Pytanie" VerticalAlignment="Top" FontFamily="Arial" FontSize="20" Margin="-83,71,0,0" Foreground="#FF353535" FontWeight="Bold"/>
<TextBlock Grid.Column="1" HorizontalAlignment="Center" Text="2" VerticalAlignment="Top" Foreground="#FFB41019" Margin="17,59,0,0" FontFamily="Arial" FontWeight="Bold" FontSize="33" />
<TextBlock Grid.Column="1" HorizontalAlignment="Center" Text="z" VerticalAlignment="Top" Foreground="#FF353535" Margin="56,71,0,0" FontFamily="Arial" FontWeight="Bold" FontSize="20" />
<TextBlock Grid.Column="1" HorizontalAlignment="Center" Text="14" VerticalAlignment="Top" Foreground="#FF353535" Margin="109,59,0,0" FontFamily="Arial" FontWeight="Bold" FontSize="33" />
<TextBlock Grid.Column="1" HorizontalAlignment="Center" Text="poziom" VerticalAlignment="Top" FontFamily="Arial" FontSize="16" Margin="-88,96,0,0" Foreground="#FF353535" FontWeight="Bold"/>
<TextBlock Grid.Column="1" HorizontalAlignment="Center" Text="licealista" VerticalAlignment="Top" FontFamily="Arial" FontSize="16" Margin="47,96,0,0" Foreground="#FFB41019" FontWeight="Bold"/>
<ListView Name="listView1" Grid.Column="1" Grid.Row="1" >
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Width="Auto" Height="50" HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding tresc_pytania}" VerticalAlignment="Top" Foreground="Black" FontFamily="Arial" FontSize="24"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
class pytania
{
[PrimaryKey]
public int id_pytania { get; set; }
public string tresc_pytania { get; set; }
public int poziom_trudnosci { get; set; }
public string odpowiedz1 { get; set; }
public string odpowiedz2 { get; set; }
public string odpowiedz3 { get; set; }
public string odpowiedz4 { get; set; }
public int dobra_odpowiedz { get; set; }
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "baza.ext");
using (var dbConn = new SQLite.SQLiteConnection(dbPath))
{
var query = dbConn.Table<pytania>();
listView1.ItemsSource = query.ToList();
}
}
Hope to hear from you some piece of advice.
Best regards,
Tomas

Related

Change color when selected on UWP C#

I need to change the color of a rectangle in a GridView when the item is selected.
Unselected item
Selected item
My Main Page in XAML.
<Page
x:Class="GridViewWithSelectedItem.Views.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:views="using:GridViewWithSelectedItem.Views"
Style="{StaticResource PageStyle}"
mc:Ignorable="d">
<Page.Resources>
<DataTemplate x:Key="TileTemplate" x:DataType="views:Article">
<Border BorderThickness="2,2,2,2" BorderBrush="#FF868484" Margin="3,3,3,3" HorizontalAlignment="Stretch" MaxWidth="600" MinWidth="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="60"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Rectangle Fill="Black" Grid.RowSpan="3"/>
<StackPanel Orientation="Horizontal" Grid.Row="0" Grid.Column="1">
<TextBlock FontSize="20" Margin="0,0,5,0" TextWrapping="Wrap" Foreground="DarkBlue" FontWeight="Bold" Text="{x:Bind Number}"/>
<TextBlock FontSize="20" TextWrapping="Wrap" Foreground="DarkBlue" Text="{x:Bind Title}" FontWeight="Bold"/>
</StackPanel>
<TextBlock Grid.Row="1" Grid.Column="1" FontSize="20" Text="{x:Bind Description}" TextWrapping="WrapWholeWords"/>
<StackPanel Background="LightBlue" Padding="5,0,0,0" Grid.Row="2" Grid.Column="1">
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="20" Margin="0,0,5,0" TextWrapping="Wrap">Date :</TextBlock>
<TextBlock Foreground="Red" FontSize="20" TextWrapping="Wrap" Text="{x:Bind Date}" FontWeight="Bold"/>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</DataTemplate>
</Page.Resources>
<Grid x:Name="ContentArea" Margin="{StaticResource MediumLeftRightMargin}">
<Grid Background="White" VerticalAlignment="Top" HorizontalAlignment="Stretch" Margin="0,25,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="600"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="60"/>
<RowDefinition Height="800"/>
</Grid.RowDefinitions>
<TextBlock Text="The Guardian" FontSize="35" FontWeight="Bold" Grid.ColumnSpan="2" HorizontalAlignment="Center"/>
<GridView
BorderThickness="2,2,0,2" BorderBrush="#FF868484"
MinWidth="600"
Grid.Column="0"
Grid.Row="1"
Padding="5,5,5,5"
HorizontalAlignment="Center"
CanDragItems="False"
IsItemClickEnabled="true"
IsTapEnabled="False"
IsSwipeEnabled="False"
ItemsSource="{x:Bind Articles}"
ItemTemplate="{StaticResource TileTemplate}"
SelectedItem="{x:Bind Mode=TwoWay, Path=SelectedArticle}"
/>
<RelativePanel Grid.Row="1" Grid.Column="1" Background="WhiteSmoke" BorderThickness="2" BorderBrush="#FF868484" Padding="10">
<Grid RelativePanel.AlignLeftWithPanel="True" RelativePanel.AlignRightWithPanel="True">
<Grid VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Grid.Row="0">
<TextBlock FontSize="20" Margin="0,0,5,0" TextWrapping="Wrap" Foreground="DarkBlue" FontWeight="Bold" Text="{x:Bind Path=SelectedArticle.Number, Mode=OneWay}"/>
<TextBlock FontSize="20" TextWrapping="Wrap" Foreground="DarkBlue" Text="{x:Bind Path=SelectedArticle.Title, Mode=OneWay}" FontWeight="Bold"/>
</StackPanel>
<TextBlock Grid.Row="1" FontSize="20" Text="{x:Bind Path=SelectedArticle.Description, Mode=OneWay}" TextWrapping="WrapWholeWords"/>
</Grid>
</Grid>
<RelativePanel Background="LightBlue" Padding="5,0,0,0" RelativePanel.AlignBottomWithPanel="True" RelativePanel.AlignLeftWithPanel="True" RelativePanel.AlignRightWithPanel="True">
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="20" Margin="0,0,5,0" TextWrapping="Wrap">Date :</TextBlock>
<TextBlock Foreground="Red" FontSize="20" TextWrapping="Wrap" Text="{x:Bind Path=SelectedArticle.Date, Mode=OneWay}" FontWeight="Bold"/>
</StackPanel>
</RelativePanel>
</RelativePanel>
</Grid>
</Grid>
</Page>
And the class of my XAML Page.
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Windows.UI.Xaml.Controls;
namespace GridViewWithSelectedItem.Views
{
public sealed partial class MainPage : Page, INotifyPropertyChanged
{
public ObservableCollection<Article> Articles;
private Article _selectedArticle;
public Article SelectedArticle
{
get { return _selectedArticle; }
set { Set(ref _selectedArticle, value); }
}
public MainPage()
{
InitializeComponent();
Articles = new ObservableCollection<Article>();
Articles.Add(new Article(0, "Uighurs", "Being young' leads to detention in China's Xinjiang region", DateTime.Parse("09/12/2020")));
Articles.Add(new Article(1, "Brexit", "Chances of Brexit deal hang on Boris Johnson and Ursula von der Leyen dinner", DateTime.Parse("09/12/2020")));
Articles.Add(new Article(2, "Environment", "Secretive ‘gold rush’ for deep-sea mining dominated by handful of firms", DateTime.Parse("09/12/2020")));
Articles.Add(new Article(3, "Juukan Gerge induiry", "Juukan Gorge inquiry: Rio Tinto's decision to blow up Indigenous rock shelters 'inexcusable'", DateTime.Parse("09/12/2020")));
Articles.Add(new Article(4, "Australia", "British journalist uncovered Australian woman's alleged plan to kill parents on dark web, police say", DateTime.Parse("09/12/2020")));
Articles.Add(new Article(5, "Coronavirus", "Nine out of 10 in poor nations to miss out on inoculation as west buys up Covid vaccines", DateTime.Parse("09/12/2020")));
}
public event PropertyChangedEventHandler PropertyChanged;
private void Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
{
if (Equals(storage, value))
{
return;
}
storage = value;
OnPropertyChanged(propertyName);
}
private void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public class Article
{
public int Number { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime Date { get; set; }
public Article(int number, string title, string description, DateTime date)
{
Number = number;
Title = title;
Description = description;
Date = Date;
}
}
}
I see AutomationProperty.name can help me but i don't understand how to use it.
I found a way to change the color of a selected item in my class but i need to recreate the collection and i cost lot of resources. I think its possible to make it in XAML code.
Edit: I made a simple exemple of my code.
OneDrive link
You could add a Brush property into the Article class, and bind the Brush property to Rectangle.Fill property of your DataTemplate to change the color when an item of GridView control is selected.
Please check the following code:
In DataTemplate of your xaml file:
<Rectangle x:Name="rectangle" Fill="{x:Bind Brush}" Grid.RowSpan="3"/>
……
<GridView …… SelectionChanged="GridView_SelectionChanged" />
In code-behind:
public class Article
{
……
public SolidColorBrush Brush { get; set; }
public Article(int number, string title, string description, DateTime date)
{
……
Brush = new SolidColorBrush(Colors.Black);
}
}
Add a _preSelectedArticle property to save the previous item in MainPage class:
private Article _preSelectedArticle;
Change the value of Brush property of selected item and previous selected item:
private void GridView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(_preSelectedArticle==null)
{
SelectedArticle.Brush.Color = Colors.Green;
_preSelectedArticle = SelectedArticle;
}
if (_preSelectedArticle!=null&&_preSelectedArticle!= SelectedArticle)
{
_preSelectedArticle.Brush.Color = Colors.Black;
SelectedArticle.Brush.Color = Colors.Green;
_preSelectedArticle = SelectedArticle;
}
}

Binding nested listviews to class

This is my class:
public class ZuResults
{
public Direct_Matches[] direct_matches { get; set; }
public int found { get; set; }
public string query { get; set; }
public ZuResults()
{
}
}
public class Direct_Matches
{
public object[] data { get; set; }
public string[] headwords { get; set; }
public Metadata metadata { get; set; }
}
public class Metadata
{
public string pos { get; set; }
public string lang { get; set; }
}
This is the ListView to which I am trying to bind this class:
<ListView Grid.Row="0" Margin="0,50,0,0" x:Name="listZuResults"
SelectionMode="Single" Background="White"
ScrollViewer.VerticalScrollBarVisibility="Auto" ItemsSource="{Binding}"
BorderThickness="0,0,1,0" BorderBrush="DarkGray">
<ListView.ItemTemplate>
<DataTemplate>
<Grid BorderThickness="1,1,1,2" BorderBrush="LightGray" Width="350">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StackPanel VerticalAlignment="Center">
<TextBlock Margin="0,0,0,0" Grid.Row="0" x:Name="Query" Foreground="{Binding FontColor}" TextWrapping="Wrap" Text="Query" FontSize="15" FontWeight="Bold"/>
<TextBlock Margin="0,0,0,0" Grid.Row="0" x:Name="txtQuery" Foreground="{Binding FontColor}" TextWrapping="Wrap" Text="{Binding query, Mode=TwoWay}" FontSize="12"/>
<TextBlock Margin="0,0,0,0" Grid.Row="0" x:Name="Found" Foreground="{Binding FontColor}" TextWrapping="Wrap" Text="Results found" FontSize="15" FontWeight="Bold"/>
<TextBlock Margin="0,0,0,0" Grid.Row="0" x:Name="txtFound" Foreground="{Binding FontColor}" TextWrapping="Wrap" Text="{Binding found, Mode=TwoWay}" FontSize="12"/>
<ListView ItemsSource="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},Path=direct_matches[1]}">
<DataTemplate>
<Grid BorderThickness="1,1,1,2" BorderBrush="LightGray" Width="350">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StackPanel VerticalAlignment="Center">
<TextBlock Margin="0,0,0,0" Grid.Row="0" x:Name="Metadata" Foreground="{Binding FontColor}" TextWrapping="Wrap" Text="Metadata" FontSize="15" FontWeight="Bold"/>
<ListView ItemsSource="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},Path=metadata}">
<TextBlock Margin="0,0,0,0" Grid.Row="0" x:Name="Pos" Foreground="{Binding FontColor}" TextWrapping="Wrap" Text="Pos" FontSize="15" FontWeight="Bold"/>
<TextBlock Margin="0,0,0,0" Grid.Row="0" x:Name="txtPos" Foreground="{Binding FontColor}" TextWrapping="Wrap" Text="{Binding pos}" FontSize="12"/>
</ListView>
</StackPanel>
</Grid>
</DataTemplate>
</ListView>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
When I set the ItemsSource of listZuResults in my MainPage.xaml code-behind, the only values that actually appear when I debug are those of txtQuery and txtFound. How do I display the rest of the data, for example 'pos' and 'lang'?

Win 8 App Set text in data template

Im trying to learn how to make datatemplate in listviews in my win 8 app
I have the following code in my Xaml code
<!-- Vertical scrolling item list -->
<ListView x:Name="itemListView"
Margin="120,0,0,60"
ItemsSource="{Binding Source={StaticResource itemsViewSource}}"
SelectionChanged="ItemListView_SelectionChanged">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Height="110" Margin="6">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}" Width="110" Height="110">
<Image Source="{Binding Image}" Stretch="UniformToFill"/>
</Border>
<StackPanel Grid.Column="1" VerticalAlignment="Top" Margin="10,0,0,0">
<TextBlock Text="{Binding Title}" TextWrapping="NoWrap" FontFamily="Global User Interface"/>
<TextBlock Text="{Binding Subtitle}" TextWrapping="NoWrap"/>
<TextBlock Text="{Binding Description}" MaxHeight="60" FontFamily="Global User Interface"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
What I cant work out is how to set the text for the three text blocks Title,Subtitle & Description as well as the Picture in Image
Usually When the page loads I use the following in my itemListView_Loaded(object sender, RoutedEventArgs e) method
itemListView.Items.Add(Convert.ToString(correct) + ". " + line.Split(',')[6]);
But how do I do it Im really stumped
Any help appreciated
Mark
You'll have to make a class which includes those properties.
public class MyItem
{
public string Title { get; set; }
public string Subtitle { get; set; }
public string Description { get; set; }
public string Source { get; set; }
}
Then when you add items:
var item = new MyItem();
item.Title = "Title";
item.Subtitle = "Subtitle";
item.Description = "Some example description.";
item.Source = "Assets/SomeFolder/SomeImage.png";
itemListView.Items.Add(item);
That worked in my app (AirPett Transit)

Values from database not showing up on xaml page after using groupby statement

I have a dto,method and xaml file below. The method returns duplicates which is fine. I only want to display one on my xaml page. I used a groupby and I was able
to display one item but the values for RouteNbr and Day are not displayed on the xaml page.
Do you know what am doing wrong?
public class CSDto
{
public Int32 ID { get; set; }
public Int32 RouteNbr { get; set; }
public Int32 Day { get; set; }
public String Month { get; set; }
public String Year { get; set; }
}
private void GetAllCsrActPlansByCsrId(Int32 CssId)
{
try
{
string getCs = Convert.ToString(CssId);
var getRouteInfoProfile = MySol.GetByCustomerNbr(getCs);
var queryResult = getRouteInfoProfile;
grdVwRouteAct.DataContext = queryResult.GroupBy(g=>g.RouteNbr).Distinct();
}
catch (Exception ex)
{
customutility.ApplicationErrorlog(UserID, ex.Message, DateTime.Now.ToString());
}
}
<GridView.ItemTemplate>
<DataTemplate>
<Button Style="{StaticResource CSRProfile}" Margin="0" Padding="0" Height="Auto" Width="Auto" Background="MediumAquamarine">
<StackPanel Tag="cpActionPlanBlock" Width="275" Height="90" HorizontalAlignment="Left" VerticalAlignment="Center" Orientation="Horizontal" Margin="0">
<Image Source="/Assets/Images/CSRProfile-checkicon.gif" Width="49" Height="65" VerticalAlignment="Center" Margin="10"/>
<StackPanel Orientation="Vertical" VerticalAlignment="Center" Margin="10,0">
<StackPanel Orientation="Horizontal">
<TextBlock Tag="cpRouteNumber" Style="{ThemeResource BasicFontStyle4B}" Text="{Binding RouteNbr}" VerticalAlignment="Top" Margin="0,0,0,5"/>
<TextBlock Style="{ThemeResource BasicFontStyle4B}" Text="-" VerticalAlignment="Top" Margin="5,0,5,0"/>
<TextBlock Tag="cpDay" x:Uid="queueItemType" Style="{ThemeResource BasicFontStyle4B}" Text="{Binding Day}" VerticalAlignment="Top" Margin="0,0,0,5"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Tag="cpNumberofActions" Style="{ThemeResource BasicFontStyle4B}" Text="[Y]" VerticalAlignment="Top" Margin="0,0,5,0"/>
<TextBlock Tag="cpLblActions" Style="{ThemeResource BasicFontStyle4B}" Text="Actions" x:Uid="cpActions" VerticalAlignment="Top" Margin="0,0,15,5"/>
</StackPanel>
</StackPanel>
</StackPanel>
</Button>
</DataTemplate>
</GridView.ItemTemplate>

ListBox Data Control Isn't Showing Information

First time using a ListBox and after following this , I'm having issues having data actually display. The ListBox is just empty and white with no text in it.
I made a separate textbox to test an individual "Tweet" object out and it is indeed outputting what I want it to. I think my issue either lies in XAML or Tweets. But nothing looks out of place.
Tracing reveals that Tweets successfully adds a proper Tweet object with what I need. But my ListBox Count is always 0.
<Grid Opacity="0.8">
<Grid.Resources>
<local:Tweets x:Key="tweets"/>
</Grid.Resources>
<Rectangle Fill="Gray" Margin="1523,0,0,729" Height="321" Width="389">
<Rectangle.Effect>
<DropShadowEffect/>
</Rectangle.Effect></Rectangle>
<ListBox ItemsSource="{StaticResource tweets}" Height="321" Margin="340,40,1096,0" x:Name="twitterBox" VerticalAlignment="Top" Width="476">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<!--<Image Source="{Binding imgSrc}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/>-->
<StackPanel Width="370">
<TextBlock Text="{Binding user}" FontSize="28" />
<TextBlock Text="{Binding tweet}" TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
In my cs:
public class Tweet
{
public String imgSrc { get; set; }
public String user { get; set; }
public String tweet { get; set; }
public Tweet(String user, String tweet, String img)
{
this.imgSrc = img;
this.user = user;
this.tweet = tweet;
}
}
public class Tweets : ObservableCollection<Tweet>
{
public Tweets()
{
}
public void addTweet(Tweet tweet)
{
Add(tweet);
}
}
public void SomeFunction()
{
Tweets myTwitter = new Tweets();
myTwitter.addTweet(new Tweet(tweet.User.ScreenName, tweet.Text, tweet.User.ProfileImageUrl));
}
ItemTemplate code is ok but you should remove this Margin="1523,0,0,729".
ListBox is empty because items source is empty. You should add some items.
To add items in XAML you should add default constructor to Tweet class.
public class Tweet
{
public String imgSrc { get; set; }
public String user { get; set; }
public String tweet { get; set; }
public Tweet(){}
public Tweet(String user, String tweet, String img)
{
this.imgSrc = img;
this.user = user;
this.tweet = tweet;
}
}
And now you can write something like this:
...
<Grid.Resources>
<local:Tweets x:Key="tweets">
<local:Tweet imgSrc="imgSrc1" user="user1" tweet="tweet1" />
<local:Tweet imgSrc="imgSrc2" user="user2" tweet="tweet2" />
</local:Tweets>
</Grid.Resources>
...
Result:
Add items in code-behind.
To do that you should use function: FindResource (msdn).
XAML:
<Grid Name="mainGrid" Opacity="0.8">
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.Resources>
<local:Tweets x:Key="tweets">
<local:Tweet imgSrc="imgSrc1" user="user1" tweet="tweet1" />
<local:Tweet imgSrc="imgSrc2" user="user2" tweet="tweet2" />
</local:Tweets>
</Grid.Resources>
<Button Content="Add new item" Click="Button_Click" />
<ListBox x:Name="twitterBox" ItemsSource="{StaticResource tweets}"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
Grid.Row="1">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<!--<Image Source="{Binding imgSrc}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/>-->
<StackPanel Width="370">
<TextBlock Text="{Binding user}" FontSize="28" />
<TextBlock Text="{Binding tweet}" TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
Code-behind:
private void Button_Click(object sender, RoutedEventArgs e)
{
var coll = mainGrid.FindResource("tweets") as Tweets;
if (coll != null)
{
coll.Add(new Tweet("user", "name", "url"));
}
}
Second solution:
The better solution will be if you will create an instance of class Tweets in code behind.
XAML:
<Grid Name="mainGrid" Opacity="0.8">
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Content="Add new item" Click="Button_Click" />
<ListBox x:Name="twitterBox" ItemsSource="{Binding tweets}"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
Grid.Row="1">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<!--<Image Source="{Binding imgSrc}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/>-->
<StackPanel Width="370">
<TextBlock Text="{Binding user}" FontSize="28" />
<TextBlock Text="{Binding tweet}" TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
Code-behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
tweets = new Tweets();
tweets.Add(new Tweet("user1", "name1", "url1"));
tweets.Add(new Tweet("user2", "name2", "url2"));
tweets.Add(new Tweet("user3", "name3", "url3"));
this.DataContext = this;
}
public Tweets tweets { get; set; }
private void Button_Click(object sender, RoutedEventArgs e)
{
tweets.Add(new Tweet("user4", "name4", "url4"));
}
}
You add tweets to a different collection than the one displayed by the listbox.

Categories