What I am trying to do is, get the property value of the selected item in the list box.
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
//listBox1.Items.Clear();
IList<FoodViewModel> food = this.Getfoodlist();
List<Foodlist> foodItems = new List<Foodlist>();
foreach (FoodViewModel foodlist in food)
{
int foodID = foodlist.C_ID;
string foodDetail = foodlist.FoodDetail;
string foodTime = foodlist.FoodTime;
string foodDate = foodlist.DateofFood;
foodItems.Add(new Foodlist() { C_ID = foodID, FoodTime = foodTime, DateofFood = foodDate, FoodDetail = foodDetail});
}
listBox1.ItemsSource = foodItems;
}
public class Foodlist
{
public int C_ID { get; set; }
public string DateofFood{ get; set;}
public string FoodTime{ get; set;}
public string FoodDetail{ get; set;}
}
XAML CODE-
<ListBox Height="528" HorizontalAlignment="Left" Margin="1,4,0,0" Name="listBox1" VerticalAlignment="Top" Width="453">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Name="foodDetail"
Text="{Binding FoodDetail}" />
<TextBlock Name="date"
Text="{Binding DateofFood}" />
<TextBlock Name="time"
Text="{Binding FoodTime}" />
<TextBlock Name="ID"
Text="{Binding C_ID}" Visibility="Collapsed" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Now, what I want to get is the C_ID(value) of selected listbox item. Any suggestions?
It would be something like this:
private void listBox1_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0)
{
var c_id = (e.AddedItems[0] as Foodlist).C_ID;
}
}
and
Page_Ctor --> listBox1.SelectionChanged += listBox1_SelectionChanged;
cheers,
where do I place this "Page_Ctor --> listBox1.SelectionChanged += listBox1_SelectionChanged;"
Here :
<ListBox .... SelectionChanged="listBox1_SelectionChanged">
Related
I have a list view with one item for this moment.
<ContentPage.Content>
<StackLayout>
<ListView x:Name="MyListView"
CachingStrategy="RecycleElement"
SelectionMode="Single">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Text}" Detail="{Binding Detail}" Something to identify item individually ??? />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button Text="Commencer" VerticalOptions="End" HorizontalOptions="Center" Clicked="StartProcessButton"/>
</StackLayout>
</ContentPage.Content>
I want to get an id or name or something who can individually get this item in my viewModel.
For example If I have an id system on this item :
void Action() {
if (listView.itemSelected.id == 1) {
then ....
}
}
I'm looking for this kind of thing. I checked google but I didn't found something for me.
You could create a id property.
Contact.cs
public class Contacts
{
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string address;
public string Address
{
get { return address; }
set { address = value; }
}
private string image;
public string Image
{
get { return image; }
set { image = value; }
}
}
MainPage.xaml
<ListView
x:Name="ContactsList"
IsVisible="True"
ItemsSource="{Binding MyList}" ItemSelected="ContactsList_ItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Image
HeightRequest="50"
Source="{Binding Image}"
WidthRequest="50" />
<Label Text="{Binding Id}" />
<Label Text="{Binding Name}" />
<Label Text="{Binding Address}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
MainPage.xaml.cs
public partial class MainPage : ContentPage
{
private ObservableCollection<Contacts> myList;
public ObservableCollection<Contacts> MyList
{
get { return myList; }
set { myList = value; }
}
public MainPage()
{
InitializeComponent();
this.BindingContext = this;
MyList = new ObservableCollection<Contacts>();
for (int i = 1; i < 10; i++)
{
MyList.Add(new Contacts() { Id = i, Name = "Student" + i.ToString(), Address = "Address" + i.ToString(), Image = "usa.png" });
}
ContactsList.ItemsSource = MyList;
}
private void ContactsList_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var item = (Contacts)e.SelectedItem;
if (item.Id == 1)
{
//.......do something you want
DisplayAlert("Id", "the id of item is 1", "Cancel");
}
}
}
In the ContactsList_ItemSelected event, you could get the ID from the e.SelectedItem. I use DisplayAlert to show the result.
I have a problem with the listviewItem, is that when you change the data if they do it but they are not saved in the interface when you click on another item
This problem happens when binding the textbox to the listviewItem
MainPage.xaml
<Grid RequestedTheme="Light">
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="818*" />
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<TextBox
x:Name="titulo"
Grid.Row="0"
FontSize="40"
PlaceholderText="Ingresa tu titulo"
KeyDown="Titulo_KeyDown"
/>
<StackPanel Grid.Row="1" Orientation="Horizontal">
<ListView
x:Name="listNotas"
Width="450"
Background="DimGray"
SelectionChanged="ListNotas_SelectionChanged">
<ListView.ItemTemplate>
<DataTemplate >
<StackPanel>
<TextBlock Text="{Binding title, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<RichEditBox
x:Name="editor"
Width="760"
HorizontalAlignment="Stretch" />
</StackPanel>
<GridView
Name="stpanel"
Grid.Row="2"
Height="50">
<TextBlock Text="" Name="Tester"/>
</GridView>
MainPage.xaml.cs
public string editpath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Notas.json" );
public ObservableCollection<Notes> Mynotes;
public MainPage()
{
this.InitializeComponent();
// Load data of Notas.json to Listview
LoadUpdate();
}
private void LoadUpdate()
{
using (StreamReader file = File.OpenText(editpath))
{
var json = file.ReadToEnd();
baseNotes mainnotes = JsonConvert.DeserializeObject<baseNotes>(json);
Mynotes = new ObservableCollection<Notes>();
foreach (var item in mainnotes.notes)
{
Mynotes.Add(new Notes { title = item.title });
}
listNotas.ItemsSource = null;
listNotas.ItemsSource = Mynotes;
listNotas.SelectedIndex = 0;
}
}
private void ListNotas_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string json = File.ReadAllText(editpath);
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
titulo.Text = jsonObj["notes"][listNotas.SelectedIndex]["title"];
}
private void Titulo_KeyDown(object sender, KeyRoutedEventArgs e)
{
#region
string json = File.ReadAllText(editpath);
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
int indice = listNotas.SelectedIndex;
jsonObj["notes"][indice]["title"] = titulo.Text;
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj);
File.WriteAllText(editpath, output);
// Show json file text in RicheditBox
editor.TextDocument.SetText(Windows.UI.Text.TextSetOptions.None, output);
//Problem
Binding myBinding = new Binding();
myBinding.Source = Mynotes[indice];
myBinding.Path = new PropertyPath("title");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(titulo, TextBox.TextProperty, myBinding);
#endregion
}
Model: Notes.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
namespace Realtimejsonedit
{
public class Notes : INotifyPropertyChanged
{
public int created { get; set; }
//public string title { get; set; }
private string Title;
public string title
{
get { return Title; }
set {
Title = value;
NotifyPropertyChanged("title");
}
}
public string text { get; set; }
public int id { get; set; }
public int updated { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class baseNotes
{
public List<Notes> notes { get; set; }
}
}
as I say the problem as I am doing the binding but when executing ListNotas.SelectionChanged the values that were saved in the json file are changed, but they do not remain in the listviewitem, although the binding is in the Keydown event and not in ListNotas. SelectionChanged.
the problem:
https://i.imgur.com/IGcd8iz.gif
What I want to achieve:
https://i.imgur.com/KnkbQw9.gif
UWP - How to save ListViewItem state if the data source has changed?
The problem is that you set bind repeatedly in Titulo_KeyDown event. For your requirement, you could bind ListView SelectItem once. For more please refer the following steps:
ViewModel
public class ViewModel : INotifyPropertyChanged
{
public string editpath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Notas.json");
public ObservableCollection<Notes> Mynotes { get; set; }
public ViewModel()
{
LoadUpdate();
SetSelectIndex(0);
}
private void SetSelectIndex(int index)
{
SelectItem = Mynotes[index];
}
private void LoadUpdate()
{
using (StreamReader file = File.OpenText(editpath))
{
var json = file.ReadToEnd();
baseNotes mainnotes = JsonConvert.DeserializeObject<baseNotes>(json);
Mynotes = new ObservableCollection<Notes>();
foreach (var item in mainnotes.notes)
{
Mynotes.Add(new Notes { title = item.title });
}
}
}
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private Notes _selectItem;
public event PropertyChangedEventHandler PropertyChanged;
public Notes SelectItem
{
get
{
return _selectItem;
}
set
{
_selectItem = value;
OnPropertyChanged();
}
}
}
Xaml
<Page.DataContext>
<local:ViewModel />
</Page.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="818*" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<TextBox
x:Name="titulo"
Grid.Row="0"
FontSize="40"
PlaceholderText="Ingresa tu titulo"
Text="{Binding SelectItem.title, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
TextChanged="Titulo_TextChanged"
/>
<StackPanel Grid.Row="1" Orientation="Horizontal">
<ListView
x:Name="listNotas"
Width="450"
Background="DimGray"
ItemsSource="{Binding Mynotes}"
SelectedItem="{Binding SelectItem, Mode=TwoWay}"
>
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding title, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<RichEditBox
x:Name="editor"
Width="760"
HorizontalAlignment="Stretch"
/>
</StackPanel>
<GridView
Name="stpanel"
Grid.Row="2"
Height="50"
>
<TextBlock Name="Tester" Text="" />
</GridView>
</Grid>
Code behind (write the data to json)
public sealed partial class MainPage : Page
{
private dynamic jsonObj;
public string editpath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Notas.json");
public ObservableCollection<Notes> Mynotes;
public MainPage()
{
this.InitializeComponent();
string json = File.ReadAllText(editpath);
jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
}
private void Titulo_TextChanged(object sender, TextChangedEventArgs e)
{
#region
int indice = listNotas.SelectedIndex;
jsonObj["notes"][indice]["title"] = titulo.Text;
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj);
editor.TextDocument.SetText(Windows.UI.Text.TextSetOptions.None, output);
File.WriteAllText(editpath, output);
#endregion
}
}
This is sample project.
I'm trying to make a ListBox with checkboxes into it.
In xaml I have:
<ListBox ItemsSource="{StaticResource ResourceKey=lstMaterialesCL}" SelectionMode="Multiple" Name="lstMaterial" >
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Name="chkMaterial" Content="{Binding DescCompuesta}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
and my ListBox looks as:
It is ok, but look it, when I checked "Municipales" the item in the ListBox is not selected, and when I select in the ListBox "Industriales" it is not checked
If I inspect the items selected into the ListBox it don't coincide with the items Checked
foreach (var item in lstMaterial.SelectedItems)
{
MessageBox.Show(((MaterialesCL)item).DescCompuesta);
}
It shows me "Oficiales", "Industriales" and "Destrucciones" but the user was want select "Municipales" and "Destrucciones"
How I can to make coincide the ListBox items selected with the CheckBox checked if the CheckBox checked is mandatory?
XAML:
DescCompuestaList is a list of CheckListGeneric
<ListBox ItemsSource="{Binding DescCompuestaList}" >
<ListBox.ItemTemplate>
<HierarchicalDataTemplate>
<CheckBox Content="{Binding DescCompuesta}" IsChecked="{Binding IsChecked}"/>
</HierarchicalDataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Here your CheckListGeneric class
public class CheckListGeneric: ViewModelBase
{
#region ..:: Fields ::..
private bool _isChecked;
#endregion
#region ..:: Properties ::..
public long Id { get; set; }
public string DescCompuesta{ get; set; }
public bool IsChecked
{
get { return _isChecked; }
set { _isChecked = value; OnPropertyChanged("IsChecked"); }
}
#endregion
}
You can get all selected using a simple query
var selectedItems = DescCompuestaList.Where(x => x.IsChecked)
simple as life.
How about binding CheckBox's IsChecked property to ListBoxItem's IsSelected property.
Something like: IsChecked={Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}
In your example:
<ListBox ItemsSource="{StaticResource ResourceKey=lstMaterialesCL}" SelectionMode="Multiple" Name="lstMaterial" >
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Name="chkMaterial" Content="{Binding DescCompuesta}" IsChecked={Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
For me it's always easiest way to use Blend for making templates.
Open project in blend and make one listBox, then select that ListBox and add template like in picture.
just to show purpose i have add simple checkBox and TextBlock, and you can make it as u like it.
in ViewModel i have made simple observable collection just to show purpose and bound ItemsSource to Users:
public class TestVM
{
public ObservableCollection<User> Users { get; set; }
public TestVM()
{
Users = new ObservableCollection<User>
{
new User{ IsChecked=true, Name="User1" },
new User{ IsChecked=false, Name="User2" },
new User{ IsChecked=true, Name="User3" },
new User{ IsChecked=false, Name="User3" },
};
}
}
public class User
{
public bool IsChecked { get; set; }
public string Name { get; set; }
}
This way you can make any template you like.
Wow, I tested all your suggestions, thank you so much to all, after all tests, the solution how I need it is more or less like this:
On xaml:
<StackPanel Orientation="Horizontal">
<ListBox ItemsSource="{Binding MaterialesVM}" SelectionMode="Multiple"
Name="ListBoxMateriales" Width="300" Height="200"
HorizontalAlignment="Left" VerticalAlignment="Top">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected" Value="{Binding IsChecked, Mode=TwoWay}" />
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsChecked, Mode=TwoWay}"
Content="{Binding DescCompuesta}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Name="btnPrueba" Style="{StaticResource BotonContent}"
Content="Selected" Width="80" Height="30" HorizontalAlignment="Left"
VerticalAlignment="Top"
Margin="10,0,0,0" Click="btnPrueba_Click"/>
<Button Name="btnLimpia" Style="{StaticResource BotonRechazar}"
Width="30" Height="30" Click="btnLimpia_Click" HorizontalAlignment="Left"
VerticalAlignment="Top"
Margin="5,0,0,0" ToolTipService.ToolTip="Limpia Todos"/>
<Button Name="btnMarca" Style="{StaticResource BotonAceptar}"
Width="30" Height="30" Click="btnMarca_Click" HorizontalAlignment="Left"
VerticalAlignment="Top"
Margin="5,0,0,0" ToolTipService.ToolTip="Selecciona Todos"/>
</StackPanel>
On this way I don't care on where clicked, the item will be selected or un-selected (on the CheckBox and on the ListItem)
And to see the items selected:
// To show the selected items
private void btnPrueba_Click(object sender, RoutedEventArgs e)
{
var selectedItems = MaterialesVM.Where(x => x.IsChecked);
foreach (var item in selectedItems)
{
MessageBox.Show(((MaterialesCL)item).DescCompuesta);
}
}
To select all items:
// To select all items
private void btnMarca_Click(object sender, RoutedEventArgs e)
{
var Items = ListBoxMateriales.Items;
foreach (MaterialesCL item in Items)
{
item.IsChecked = true;
}
}
To un-select all items:
// To un-select all items
private void btnLimpia_Click(object sender, RoutedEventArgs e)
{
var Items = ListBoxMateriales.Items;
foreach (MaterialesCL item in Items)
{
item.IsChecked = false;
}
}
and my classes are:
MaterialesCL.cs
public class MaterialesCL : INotifyPropertyChanged
{
public int Material { get; set; }
public string Descripcion { get; set; }
public string DescCompuesta { get; set; }
private bool _ischecked;
public bool IsChecked
{
get { return _ischecked; }
set
{
_ischecked = value;
OnPropertyChanged("IsChecked");
}
}
#region PropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
LstMaterialesCL.cs
public class LstMaterialesCL : ObservableCollection<MaterialesCL>, INotifyPropertyChanged
{
public LstMaterialesCL()
{
BasculaEntities _context = new BasculaEntities();
var Query = (from m in _context.Materiales
select new { m.Material, m.Descripcion}
).OrderBy(m => m.Material).ToList();
foreach (var item in Query)
{
this.Add(new MaterialesCL { Material = item.Material,
Descripcion = item.Descripcion, DescCompuesta = item.Material.ToString("000") + " - " + item.Descripcion,
IsChecked=false});
}
}
}
and on my UserControl MaterialesVM is an instance of LstMaterialesCL
LstMaterialesCL MaterialesVM = new LstMaterialesCL();
and so my test of ListBox with CheckBoxes works as I need.
Thank to all you I has learn so much.
I have this ListView in XAML:
<ListView x:Name="listView" Margin="10,72,10,120" Background="#7F000000" BorderBrush="#FF00AEFF" BorderThickness="1">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel BorderThickness="0,0,0,1">
<TextBlock Text="{Binding SSID}" Foreground="#FF067EB6" Margin="0,5,0,0"></TextBlock>
<TextBlock Text="{Binding BSSID}" Foreground="#FF067EB6"></TextBlock>
<TextBlock Text="{Binding NumOfBars}" Foreground="#FF067EB6"></TextBlock>
<TextBlock Text="{Binding WpsPin}" Foreground="#FF067EB6" Margin="0,0,0,5"></TextBlock>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
And something like this in the code behind:
class Networks
{
public string SSID { get; set; }
public string BSSID { get; set; }
public string NumOfBars { get; set; }
public string WpsPin { get; set; }
}
And this one to use the ListView:
listView.ItemsSource = null;
ObservableCollection<Networks> nets = new ObservableCollection<Networks>();
nets.Add(new Networks() { SSID = "SSID: " + networkSSID, BSSID = "BSSID: " + network.Bssid, NumOfBars = "Signal: " + network.SignalBars.ToString() + "/4", WpsPin = "WPS Pin: " + wpspin });
listView.ItemsSource = nets;
Now, I want to get the content of the selected item in the ItemSource and put it in a string. For example, I wanna get the "WpsPin" value of the selected item.
How can I do it?
You can subscribe to the ListView.SelectionChanged event and implement it in the code like the following:
XAML:
<ListView ... SelectionChanged="SelectionChanged">
C#:
private void SelectionChanged(object sender, SelectionChangedEventArgs e) {
Networks network = e.AddedItems.FirstOrDefault() as Networks;
if (network == null) return;
System.Diagnostics.Debug.WriteLine(network.WpsPin);
}
I have the following C# code that generate an items for list view:
//function that generated items for list view
results = //An array
foreach (var item in results)
{
var nameStr = item.FirstName + " " + item.LastName;
var descriptionStr = item.Email;
IconTextGrid.Items.Add(new { Name = nameStr, Description = descriptionStr });
}
And the XAML:
<Page.Resources>
<DataTemplate x:Key="IconTextDataTemplate">
<StackPanel Orientation="Horizontal" Width="220" Height="60" Background="#FF7CC6FF">
<StackPanel Orientation="Vertical" VerticalAlignment="Center">
<TextBlock Text="{Binding Name}" Margin="10,0,0,0" Width="170" Height="20" TextTrimming="WordEllipsis"/>
<TextBlock Text="{Binding Description}" Margin="10,0,0,0" Width="170" Height="20" TextTrimming="WordEllipsis"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</Page.Resources>
<ListView x:Name="IconTextGrid" SelectionMode="Multiple" ItemTemplate="{StaticResource IconTextDataTemplate}" Height="400" Grid.Row="5" Margin="40,20,40,10" HorizontalAlignment="Stretch" Foreground="White" SelectionChanged="IconTextGrid_SelectionChanged">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid MaximumRowsOrColumns="6"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>
and:
private void SendRequests_Click(object sender, RoutedEventArgs e)
{
string emailAdress;
for (int i = 0; i < IconTextGrid.SelectedItems.Count; i++)
{
//I need to get the description of the selected items
}
}
My question is how Ican get the value of the Description field in the item that generated?
Thanks
You can create custom type like this:
class MyType
{
string Name { get; set; }
string Description { get; set; }
}
Then change your code to:
IconTextGrid.Items.Add(new MyType{ Name = nameStr, Description = descriptionStr });
And now you can get description:
for (int i = 0; i < IconTextGrid.SelectedItems.Count; i++)
{
var item = (MyType)IconTextGrid.SelectedItems[i];
string description = item.Description;
}
You are using an anonymous type ofr the items in your listbox:
IconTextGrid.Items.Add(new { Name = nameStr, Description = descriptionStr });
You should declare a class:
public class MyItem
{
public string Name { get; set; }
public string Description { get; set; }
}
and use this class instead:
IconTextGrid.Items.Add(new MyItem { Name = nameStr, Description = descriptionStr });
The you can get SelectedItem and cast it to MyItem.