Add textblock text to favorite list on button click - c#

I have two pages: the first is mainpage.xaml and the second is favoriteslist.xaml.
In mainpage.xaml I have a text block, which shows some dynamic text automatically.
And I have a button also on mainpage.xaml.
From which I want when I click on that button, text appears on text block should go to favorite list in favoriteslist.xaml page.
If text already favorite, which text appears on text block should be removed from favorite list on button click.
So finally I need help to implement this functionality textblock which shows dynamically already created but I only need to know how to develop add to favorite functionality.
Textblock:
<TextBlock x:Name="StringTextBlock" Text="" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}" />
Button:
<Button Grid.Row="2" x:Name="AddToFavoritesButton"
Content="Add" Style="{StaticResource ButtonStyle2}" Margin="2"
Click="AddToFavoritesButton_Click"/>
C#
private void AddToFavoritesButton_Click(object sender, RoutedEventArgs e)
{
}
Listbox:
<ListBox x:Name="FavoriteListBox" />

I would use IsolatedStorageSettings to store the list and compare the dynamic text to the list in the isolatedstoragesettings upon button click. Then on FavouritesList page, set itemsource of the listbox to the list in IsolatedStorageSettings.So here are the steps to be followed:
1. Create a model/class to set the dynamic text being shown on the text block
public class favourites
{
public string myText { get; set; }
}
2. In the button click event on MainPage.xaml.cs, first set the dynamic text (where ever you are getting it from) to the text block if you need to and then create the list and/or compare
private void AddToFavoritesButton_Click(object sender, RoutedEventArgs e)
{
//your dynamic text set to textblock
StringTextBlock.Text = myDynamicText;
//Set value of your text to member variable of the model/class
favourites f = new favourites();
f.myText = myDynamicText;
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
/*Check if "FavouritesList" key is present in IsolatedStorageSettings
which means already a list had been added. If yes, retrieve the
list, compare each item with your dynamic text, add or remove
accordingly and replace the new list in IsolatedStorageSettings
with same key. */
if (settings.Contains("FavouritesList"))
{
List<favourites> l = (List<favourites>)settings["FavouritesList"];
for(int i = 0; i <= l.Count()-1; i++)
{
if (l[i].Equals(myDynamicText))
{
l.RemoveAt(i);
settings["FavouritesList"] = l;
}
else
{
l.Add(f);
settings["FavouritesList"] = l;
}
}
}
//If no key in IsolatedStorageSettings means no data has been added
//in list and IsolatedStorageSettings. So add new data
else
{
List<favourites> l = new List<favourites>();
l.Add(f);
settings["FavouritesList"] = l;
}
settings.Save();
}
Now all that is left is show the always updated list in the FavouritesList Page. I added a 'NoData' textblock that should be visible when there is nothing in the list. Else the list will be displayed.
In FavouritesList.xaml
<ListBox x:Name="FavoriteListBox" Visibility="Collapsed">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding myText}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBlock Name="NoData"
Text="No Data"
Visibility="Collapsed"
Width="50"
Height="50"/>
In FavouritesList.xaml.cs
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains("FavouritesList"))
{
List<favourites> l = (List<favourites>)settings["FavouritesList"];
if(l.Count!= 0)
{
NoData.Visibility = System.Windows.Visibility.Collapsed;
FavoriteListBox.Visibility = System.Windows.Visibility.Visible;
FavoriteListBox.ItemsSource = l;
}
}
else
{
FavoriteListBox.Visibility = System.Windows.Visibility.Collapsed;
NoData.Visibility = System.Windows.Visibility.Visible;
}
I have not tested this but should definitely work. Hope it helps!

Related

ListBox filled with binding doesn't select item on click

I'm trying to use a ListBox to choose an entry and then display a picture belonging to this selected entry. But just at the beginning I got my first problem: filling the ListBox with binding is working, but if I click on one line in my running program, it doesn't select the line. I can just see the highlighted hover effect, but not select a line. Any ideas what my mistake could be?
This is my XAML:
<ListBox x:Name="entrySelection" ItemsSource="{Binding Path=entryItems}" HorizontalAlignment="Left" Height="335" Margin="428,349,0,0" VerticalAlignment="Top" Width="540" FontSize="24"/>
And in MainWindow.xaml.cs I'm filling the ListBox with entries:
private void fillEntrySelectionListBox()
{
//Fill listBox with entries for active user
DataContext = this;
entryItems = new ObservableCollection<ComboBoxItem>();
foreach (HistoryEntry h in activeUser.History)
{
var cbItem = new ComboBoxItem();
cbItem.Content = h.toString();
entryItems.Add(cbItem);
}
this.entrySelection.ItemsSource = entryItems;
labelEntrySelection.Text = "Einträge für: " + activeUser.Id;
//show image matching the selected entry
if (activeUser.History != null)
{
int index = entrySelection.SelectedIndex;
if (index != -1 && index < activeUser.History.Count)
{
this.entryImage.Source = activeUser.History[index].Image;
}
}
}
So I can see my ListBox correctly filled, but not select anything - so I can't go on with loading the picture matching the selected entry.
I'm still quite new to programming, so any help would be great :)
EDIT: If someone takes a look at this thread later: here's the - quite obvious -solution
XAML now looks like this
<ListBox x:Name="entrySelection" ItemsSource="{Binding Path=entryItems}" HorizontalAlignment="Left" Height="335" Margin="428,349,0,0" VerticalAlignment="Top" Width="540" FontFamily="Siemens sans" FontSize="24">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Text}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Code behind to fill it:
//Fill listbox with entries for selected user
DataContext = this;
entryItems = new ObservableCollection<DataItem>();
foreach (HistoryEntry h in selectedUser.History)
{
var lbItem = new DataItem(h.toString());
entryItems.Add(lbItem);
}
this.entrySelection.ItemsSource = entryItems;
labelEntrySelection.Text = "Einträge für: " + selectedUser.Id;
And new Class DataItem:
class DataItem
{
private String text;
public DataItem(String s)
{
text = s;
}
public String Text
{
get
{
return text;
}
}
}
You are filling it with ComboBoxItem, which is not relevant to the ListBox, and also wrong by definition.
You need to have the ObservableCollection filled with data items.
Meaning, make a class that contains the data you want to store, and the ListBox will generate a ListBoxItem automatically per data item.
http://www.wpf-tutorial.com/list-controls/listbox-control/

How to create multiple buttons from existing strings in .txt file

I wonder how I can create buttons in my Toolbar by reading lines from a .txt file.
For example:
//bookmarks.txt
http://example.com
http://example2.com
http://example3.com
...
What I want is that my program on start should create a button for each line in my .txt with this event:
public void Button_Click(object sender, RoutedEventArgs e) //fire bookmark event
{
string text = e.Source.ToString().Replace("System.Windows.Controls.Button: ", "");
WebBrowser1.Navigate(text);
}
UPDATE
This is how I read the .txt:
for (int i = 0; i < File.ReadLines(#"bookmarks.txt").Count(); i++)
{
//Add button right here
}
You're trying to use WPF as if it were WinForms. This is how you would fulfil your requirements in WPF... first create a DependencyProperty collection in your Window code behind and populate it with your text entries:
public static DependencyProperty ItemsProperty = DependencyProperty.Register("Items", typeof(ObservableCollection<string>), typeof(YourWindowOrUserControl));
public ObservableCollection<string> Items
{
get { return (ObservableCollection<string>)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
...
Items = new ObservableCollection<string>(File.ReadLines(#"bookmarks.txt"));
Then you simply data bind the collection to the ToolBar.ItemsSource property and declare a DataTemplate to define what each string should look like... in your case, we'll set it as the text in a Button:
<ToolBar ItemsSource="{Binding Items}">
<ToolBar.ItemTemplate>
<DataTemplate>
<Button Content="{Binding}" Margin="1,0,0,0" />
</DataTemplate>
</ToolBar.ItemTemplate>
</ToolBar>
Of course, you'll need to set the Window.DataContext to the class with your properties... the simplest way is to set it in the code behind constructor like this:
public YourWindowOrUserControl
{
InitializeComponent();
DataContext = this;
}
You must read up about how to set the DataContext properly though, as setting it this way is easy, but not necessarily correct.
Finally, you could create a class with all the necessary properties for the Button... for example, you could add a property named Text and another called Command and then make your Items property a collection of those. Then you could data bind to it like this:
<ToolBar ItemsSource="{Binding Items}">
<ToolBar.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Text}" Command="{Binding Command}" Margin="1,0,0,0" />
</DataTemplate>
</ToolBar.ItemTemplate>
</ToolBar>
You can create buttons dynamic and add click event on fly:
Button btn = new Button();
btn.Location = new Point(yourX, yourY);
btn.Font = new Font(btn.Font.Name, 10);
btn.Text = "Text from your txt file here";
btn.ForeColor = Color.SeaShell; // choose color
btn.AutoSize = true;
btn.Click += (sender, eventArgs) =>
{
string text = btn.Text.Replace("System.Windows.Controls.Button: ", "");
WebBrowser1.Navigate(text);
};
(Insert this code in your For. Btw, you can replace the for with while. see this link)

c# How to get Listbox selection from Observable Collection

I'm probably not even asking this correctly, I am new to c#, but trying to help my 14 year-old son learn. I've created a listbox with items created with an ObservableCollection. Here is the XAML:
<ListBox x:Name="listBox1" ItemsSource="{Binding}" Margin="105,205,886,63"
IsTabStop="True" SelectionChanged="PrintText"
ScrollViewer.VerticalScrollBarVisibility="Hidden" TabIndex="5" FontSize="36"
Background="Transparent" Foreground="#FF55B64C" FontFamily="Arabic Typesetting"
FontWeight="Bold" IsDoubleTapEnabled="False" SelectionMode="Single" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Name="blockNameList" Text="{Binding name}"/>
<TextBlock Text=" #"/>
<TextBlock Name="blockIdList" Text="{Binding id}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Here is how I created the ListBox Items:
var client = new HttpClient();
var uri = new Uri("http://theurlImusing");
Stream respStream2 = await client.GetStreamAsync(uri);
// DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(RootObject));
// RootObject feed2 = (RootObject)ser2.ReadObject(respStream2);
DataContractJsonSerializer ser = null;
ser = new DataContractJsonSerializer(typeof(ObservableCollection<RootObject>));
ObservableCollection<RootObject> feed2 = ser.ReadObject(respStream2) as ObservableCollection<RootObject>;
var cardList = new List<RootObject>();
foreach (RootObject returnfeed in feed2)
{
string cid = returnfeed.id;
string cardname = returnfeed.name;
listBox1.Items.Add(new RootObject { id=cid, name=cardname });
}
I thought I would just use the SelectionChanged="PrintText" property of the listbox so that when I clicked on a listbox item, it would just change a textblock's text value. Ultimately, that is all I am trying to do...set a textblock or textbox to be equal to the "id" value that is clicked on in the ListBox.
void PrintText(object sender, SelectionChangedEventArgs args)
{
//What do I put in here??
}
Thanks very much for any insight! I need it!!
This is something that is much easier to do using data binding. You can bind the TextBlock.Text property directly to the ListBox using an ElementName binding:
<TextBox Text="{Binding ElementName=listBox1,Path=SelectedItem.id}" />
Alternatively, if you set set SelectedValuePath="id" on the ListBox, then binding to SelectedValue will give you the "id" property:
<ListBox x:Name="listBox1" SelectedValuePath="id" ... />
<TextBox Text="{Binding ElementName=listBox1,Path=SelectedValue}" />
As a side note (as #Rachel already noted in comments): you may as well just set the ItemsSource, rather than looping through and adding each manually. All you need is this:
listBox1.ItemsSource = feed2;
Edit
Ok, if you wanted to use the procedural approach, here's how you would do it. (No one would recommend this approach, especially if you're learning/teaching. Try to make full use of data binding, and view-viewmodel separation.)
void PrintText(object sender, SelectionChangedEventArgs args)
{
var listBox = (ListBox)sender;
RootObject selectedItem = listBox.SelectedItem;
someTextBox.Text = selectedItem.id;
}
If all you want to do is click an item in the ListBox and get it to show up in the TextBox, you don't need fancy binding (in that other answer) to do it. You can simply add a MouseUp event in the ListBox XAML:
MouseUp="ListBox1_MouseUp"
This would work similar to the SelectionChanged event you wanted to use.
You then right-click that function name in the XAML page and select "Go to definition". It will create the next function for you:
private void ListBox1_MouseUp(object sender, MouseButtonEventArgs e)
{
}
Simply add in there to update the TextBox you want with the SelectedItem values from sender:
private void ListBox1_MouseUp(object sender, MouseButtonEventArgs e)
{
ListBox lstBox = (ListBox)sender;
ListBoxItem item = lstBox.SelectedItem;
if (item != null) // avoids exception when an empty line is clicked
{
someBox.Text = item.name;
someOtherBox.Text = item.id;
}
}
I later found that blockNameList and blockIdList are not accessible via intellisense because they are within the DataTemplate of the ListBox, so I put someBox and someOtherBox, as references to other TextBoxes you would have to add to the XAML, outside of the ListBox. You would not re-write data inside the ListBox on the same item by clicking it. Even if you could reach the template's TextBlock to do it, you'd just be re-writing that same item with its own values, since it would be the SelectedItem!
Even though there are those that don't recommend this approach because they like binding everything - and in some cases you want binding to occur so that controls on the page update as a result of dependencies (i.e. do one thing to cause another), I find that manual methods of clicking a button/item/control to update something are just fine and avoid all the model/MVVM BS that has taken over WPF and over-complicated it.

Add Item to ListBox from TextBox

I have this ListBox:
<ListBox x:Name="PlaylistList" AlternationCount="2" SelectionChanged="DidChangeSelection">
<ListBox.GroupStyle>
<GroupStyle />
</ListBox.GroupStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And i want to add option to add new item to the ListBox. And i want to do it by adding a TextBox to the ListBox when the user press a Button and then the user press enter and add the text in the TextBox to the ListBox.
I try to add text box to the listbox but i can add only one type of ListBox.ItemTemplate, how can i handle it?
Updated to add textbox inside Listbox:
To add new item into ListBox, in Button Click code-behind do:
TextBox TextBoxItem = new TextBox();
// set TextBoxItem properties here
PlaylistList.Items.Add(TextBoxItem);
Your ListBox:
<ListBox
Name="MyListBox"
ItemsSource="{Binding Path=Reason}"
DisplayMemberPath="Description"/>
Make a ObversableCollection for the Items of the ListBox
public ObservableCollection<IdObject> items
{
get { return (ObservableCollection<IdObject>)GetValue(ApplicationsProperty); }
set { SetValue(ApplicationsProperty, value); }
}
items = new ObservableCollection<IdObject>();
My ID-Object in this case has the following properties:
private int _id = 0;
private string _description = "";
Bind the collection to the ListBox:
MyListBox.ItemsSource = items;
Then make a TextBox with a Button, and an event for pressing the button, where you add the text to the observable collection:
items.Add(new IdObject(someId, TextBox.Text));
The ListBox will update, when the ObservableCollection is changed
Write this code when your button is clicked so that the textbox text will be added to the listbox.
private void addEventButton_Click(object sender, EventArgs e)
{
// Adds events to listbox.
if (this.titleTextBox.Text != "")
{
listBox1.Items.Add(this.titleTextBox.Text);
listBox2.Items.Add(this.titleTextBox.Text);
this.titleTextBox.Focus();
this.titleTextBox.Clear();
}
}

Bound ItemsControl not updating before displaying

I have a UserControl that is comprised of a few bound ItemsControl's and strings, and based on the button that is pressed, different data is displayed. Here is an example of one of the Button's click events:
private void LeftPreviousScoresButton_Click(object sender, RoutedEventArgs e)
{
if (m_previousScoresWindow.Visibility == Visibility.Visible)
{
m_previousScoresWindow.Hide();
}
else
{
WindowTitle = "Left Side";
PreviousScoresA = m_previousLeftWristErosionScoresReaderA;
PreviousScoresB = m_previousLeftWristErosionScoresReaderB;
m_previousScoresWindow.Show();
}
}
There are several of these click event listeners which assigns WindowTitle, PreviousScoresA, and PreviousScoresB with the associated data. The UserControl then binds to them like this:
<ItemsControl Height="Auto" Width="Auto"
ItemsSource="{Binding ElementName=ParentForm, Path=PreviousScoresA}"
Grid.Row="1" />
<ItemsControl Height="Auto" Width="Auto"
ItemsSource="{Binding ElementName=ParentForm, Path=PreviousScoresB}"
Grid.Row="2" />
<TextBlock FontSize="16" FontWeight="Bold" Height="25"
Margin="5" HorizontalAlignment="Center" Foreground="Black"
Text="{Binding ElementName=ParentForm, Path=PreviousScoresWindowTitle}" />
However, when opening the window, the old data displays for a second before it is updated with the current data. I've even tried adding these calls when calling Hide() on the Window but it didn't seem to help:
WindowTitle = String.Empty;
PreviousScoresA = new ObservableCollection<PreviousScoreData>();
PreviousScoresB = new ObservableCollection<PreviousScoreData>();
Is there any way to ensure that Show() is not called until after the bound data has been updated? Thanks.
As it appears you are using an ObservableCollection, the collection should never be re-initialized. Rather, it should just be cleared and then add the new values; this is what helps keep the collection synchronized when using an ObservableCollection.
This is a bit of a shot in the dark based on your code sample; if you clear the collection when hiding and then refill them with the new values, then you should get the desired effect:
private void LeftPreviousScoresButton_Click(object sender, RoutedEventArgs e)
{
if (m_previousScoresWindow.Visibility == Visibility.Visible)
{
m_previousScoresWindow.Hide();
WindowTitle = string.Empty;
PreviousScoresA.Clear();
PreviousScoresB.Clear();
}
else
{
WindowTitle = "Left Side";
// do not re-initialize the collection; clear and add new values
// PreviousScoresA = m_previousLeftWristErosionScoresReaderA;
// PreviousScoresB = m_previousLeftWristErosionScoresReaderB;
ReFillScores(PreviousScoresA, m_previousLeftWristErosionScoresReaderA);
ReFillScores(PreviousScoresB, m_previousLeftWristErosionScoresReaderB);
m_previousScoresWindow.Show();
}
}
private void ReFillScores (ObservableCollection<PreviousScoreData> collection, IEnumerable<PreviousScoreData> values)
{
collection.Clear();
foreach(PreviousScoreData d in values)
{
collection.Add(d);
}
}

Categories