Windows phone 8.1 - text from dynamically created textBoxes - c#

I'm trying to create table scheme in Windows phone 8.1 but I have problem with saving this. I created table in XAML: Here is code
<ItemsControl x:Name="br" ItemsSource="{Binding Data}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid x:Name="Ahoj" Margin="0,0,-20,-18">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Text="{Binding name}"></TextBox>
<TextBox Grid.Column="1" Text="{Binding s1}"></TextBox>
<TextBox Grid.Column="2" Text="{Binding s2}"></TextBox>
<TextBox Grid.Column="3" Text="{Binding s3}"></TextBox>
<TextBox Grid.Column="4" Text="{Binding s3}"></TextBox>
<TextBox Grid.Column="5" Text="{Binding name}"></TextBox>
<TextBox Grid.Column="6" Text="{Binding s1}"></TextBox>
<TextBox Grid.Column="7" Text="{Binding s2}"></TextBox>
<TextBox Grid.Column="8" Text="{Binding s3}"></TextBox>
<TextBox Grid.Column="9" Text="{Binding s3}"></TextBox>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
but i don't know how to read values from this dynamically created textBoxes. I need to get the value of all the textbox. I do not need to work with them separately.
Thanks
EDIT
I try to use codes from answers and it work well, but only with first grid.
I'm creating grid dynamically too. This grid has the same name, but diferent values from Binding.
Code in answer work returning value only from first line textboxes...
Code - I'm adding items to list and after Itemsource is this list and I'm binding it to textboxes
var str = new StreamReader(contentStream);
while(str.EndOfStream !=true)
{
string line = str.ReadLine();
if (line == null)
break;
var spl = line.Split(';');
string prvni = spl[0].ToString();
if(spl[0]!="")
{
if (spl[0].Substring(0,3).Contains("-"))
{
obj.Add(new data(a+pocet.ToString(),spl[0].ToString(), spl[1].ToString(), spl[2].ToString(),"#FF00D1FF"));
}
else
obj.Add(new data(a+pocet.ToString(),spl[0].ToString(), spl[1].ToString(), spl[2].ToString(), "White"));
}
else
{
obj.Add(new data(a + pocet.ToString(), spl[0].ToString(), spl[1].ToString(), spl[2].ToString(), "White"));
}
pocet++;
}
br.ItemsSource = obj; // load list to binding
Class data
public class data
{
public string Index { get; set; }
public string s1 { get; set; }
public string s2 { get; set; }
public string s3 { get; set; }
public string color { get; set; }
public data() { }
public data(string index,string s1, string s2, string s3, string br)
{
this.Index = index;
this.s1 = s1;
this.s2 = s2;
this.s3 = s3;
this.color = br;
}
}

I've also worked with dynamic content and I used to do this: ( Adapted to your requirements )
// Cycle through every control from Ahoj
foreach (Object controlObject in Ahoj.Children) {
if (controlObject is TextBox) {
TextBox
textBox = controlObject as TextBox;
// Do your stuff here...
}
}
Since you say that you're unable to access the Grid directly ( if I understood correctly, you're adding the control by run-time code ) then you can do something like this:
try {
Grid
grid = FindName("Ahoj") as Grid;
// Cycle through every control from Ahoj
foreach (Object controlObject in grid.Children) {
if (controlObject is TextBox) {
TextBox
textBox = controlObject as TextBox;
// Do your stuff here...
}
}
} catch (Exception exception) {
// Unable to catch or cast the object
}
EDIT: If you also need to know the position of each TextBox you may use a for(;;) instead.
EDIT 15 Jan 2016: Here is the code updated based on what's been discused on comments and with the sudden realization that you could simply get the List binded to the control since the beginning:
try {
List<data>
dataList = br.ItemsSource;
/*
Do your stuff here ...
*/
} catch(Exception exception) {
// Unable to get the previously binded items
}

Not sure if this is what you are asking but if you want to create a list of all the strings in the textboxes you can do the following:
Loop through each visual child element of the "Ahoj" grid (using VisualTreeHelper.GetChild(container, index)) and check if it is a TextBox Type. In case it is request the Text property of the TextBox and add it to the list of strings.
See MSDN VisualTreeHelper for more info.

Related

Data Binding SQLIte to Listbox(containing three controls) Windows phone 8

Iam new to implementing SQLITE DB & windows phone 8 app development...
Implemeted following startegy to retreive data to listbox which contains three other controls..
here is my XAML code..
<ListBox Height="Auto" Name="TaskListBox" Margin="5,61,-1,298">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Background="Red" Height="480" Width="200">
<TextBlock Text="{Binding status }" Name="team1Name" Width="120" ></TextBlock>
<TextBlock Text="{Binding CreationDate }" Name="team3Name" Foreground="White" Width="120" HorizontalAlignment="Center"></TextBlock>
<HyperlinkButton Content="{Binding Merid_FK }" Name="team2Name" Foreground="White"/>
<TextBlock Text="{Binding status}" Name="venue" Foreground="White" Height="67" Width="78"></TextBlock>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
and my code behind
private void Insert_Click(object sender, RoutedEventArgs e)
{
using (var db = new SQLiteConnection(DB_PATH))
{
db.RunInTransaction(() =>
{
db.Insert(new tasks() { Merid_FK = 126745, status = "Y", CreationDate = DateTime.Now });
db.Insert(new tasks() { Merid_FK = 1289906, status = "N", CreationDate = DateTime.Now });
});
}
private void Retrieve_Click(object sender, RoutedEventArgs e)
{
List<tasks> listmerchant = dbConn.Query<tasks>("SELECT * from tasks where status='" + "Y" + "'").ToList<tasks>();
TaskListBox.ItemsSource = listmerchant;
}
my tasks class
public sealed class tasks
{
//[PrimaryKey,AutoIncrement]
public int Merid_FK { set; get; }
public string status { set; get; }
public DateTime CreationDate { set; get; }
public override string ToString()
{
return Merid_FK + ">> " + status + ">> " + CreationDate.ToShortDateString() ;
}
}
my problem is ,iam getting output as "16757 >> status1 >> 2012-12-20 12:20" on UI(in list box place.. not at the controls in data template).. its simply returning method placed in class tasks..please tell me how to bind data to controls placed inside the lsitbox.
i already followed lot of similar questions in stack over flow,..
Slect data from SQLite
bind data to list box
bind data dynamically
please keep height and width of listbox and controls inside listbox to "Auto" in xaml.if you used any border control..make sure width and height are set to "Auto"
Height="Auto" Width="Auto"
please check this and revert back with error picture..

How to get the column value of the selected row in wpf listview

In my listview, I've three columns, the first column is displayed as text with image and the rest of the columns just text only. The listview is coded as below:
<TabItem x:Name="HistoryTab" Header="History" Style="{StaticResource TabStyle}">
<Grid>
<ListView x:Name="HistoryTabLv" HorizontalAlignment="Left" Height="164" Width="275" VerticalAlignment="Top" SelectionChanged="HistoryTabLv_SelectionChanged" SelectionMode="Single">
<ListView.View>
<GridView>
<GridViewColumn x:Name="TimeColumn" Header="Time" Width="85">
<GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left" Margin="-5,0,0,0">
<Image x:Name="Img" Height="12" Width="12" Source="{Binding Image}" Stretch="Uniform"/>
<TextBlock Text="{Binding Time}"/>
</StackPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn x:Name="PhoneNumColumn" Header="Phone Number" Width="85" DisplayMemberBinding="{Binding PhoneNum}" />
<GridViewColumn x:Name="DirectionColumn" Header="Direction" Width="95" DisplayMemberBinding="{Binding Direction}" />
</GridView>
</ListView.View>
</ListView>
</Grid>
</TabItem>
If the action statement is true, the relevant data will be binded to each column as coded below.
private void HistoryTabLv_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (myStatement == true)
{
var uri = new Uri(#"/Resources/time.png", UriKind.Relative);
myImg = new BitmapImage(uri);
DateTime myTime = DateTime.Now;
HistoryTabLv.Items.Insert(0, new { Image = myImg, Time = myTime.ToString("hh:mm:ss tt"), PhoneNum = calledNum,
Direction = "Called out" });
}
}
In winform, if I want to get the second column value of the selected row, it is coded like this: (based on what I've searched)
string secondCol = lv.SelectedItems[0].SubItems[1].Text;
I want to get the second column value of the selected row (in my case is the PhoneNum column), how can I do that in WPF. I tried with the code below but it doesn't work. Please help.
string myText = (string)((DataRowView)HistoryTabLv.SelectedItems[0])["PhoneNum"];
In WPF ListViewItem is just a wrapper for your content object and SelectedItem(s) will be of the same type as item in your source collection so normally you would cast HistoryTabLv.SelectedItem to that type but because, as far as I can see, you use anonymous type it makes it a bit more difficult. I think the easiest way is around your problem is to use dynamic
dynamic selectedItem = HistoryTabLv.SelectedItem;
var phoneNum = selectedItem.PhoneNum;
or
dynamic selectedItem = HistoryTabLv.SelectedItems[0];
var phoneNum = selectedItem.PhoneNum;
EDIT
If you would create class for you item like
public class MyItemClass {
public string Image { get; set; }
public string Time { get; set; }
public string PhoneNum { get; set; }
public string Direction { get; set; }
}
and create your item like
new MyItemClass {
Image = myImg,
Time = myTime.ToString("hh:mm:ss tt"),
PhoneNum = calledNum,
Direction = "Called out"
}
then you could cast SelectedItem(s) to your item class like
var selectedItem = (MyItemType)HistoryTabLv.SelectedItem

Reach a TextBlock from a specific ListViewItem from the ListView in Windows Phone 8.1 XAML programmatically

I am a new developer on Windows Phone 8.1, I am try to reach a specific ListView item from the ListView collection and be able to color it or color the TextBock inside of it, But I can't reach the item or reach any of items inside of ListView, Please take a look for my below code :
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
SQLiteRT db1 = new SQLiteRT();
var db_connection = await db1.Connection("MyDB.sqlite");
List<MyTBL> t_list = db1.GetTable("SELECT * FROM MyTBL LIMIT 4 ORDER BY RANDOM() ;");
db_connection.Close();
LV_Options.ItemsSource = t_list;
}
// my List View called LV_Options
private void LV_Options_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListView lv1 = sender as ListView;
if (lv1 == null)
return;
MyTBL wrd = lv1.SelectedItem as MyTBL;
if (wrd == null)
return;
TextBlock tb = lv1.FindName("TB_AMean1") as TextBlock;
tb.FontSize = 17; // here I got debug error (it not worked !!!!!!!)
var item = LV_Options.Items.ElementAt(3); // this seems not work also !!!!
item.BackColor = Color.LightSteelBlue;
}
As you can see above, I tried to reach a specific item by LV_Options.Items.ElementAt(3) but it doesn't work! I also tried to reach the TextBlock from the selected List view item, but also not worked !
(Updated)
XAML code :
<!-- Title Panel -->
<StackPanel Grid.Row="0" Margin="19,0,0,0">
<TextBlock Name="TB_Rslt" Text="Here result of your answer" Style="{ThemeResource TitleTextBlockStyle}" Margin="0,12,0,0"/>
<TextBlock Text="page title" Margin="0,-6.5,0,26.5" Style="{ThemeResource HeaderTextBlockStyle}" CharacterSpacing="{ThemeResource PivotHeaderItemCharacterSpacing}"/>
</StackPanel>
<!--TODO: Content should be placed within the following grid-->
<Grid Grid.Row="1" x:Name="ContentRoot" Margin="19,10,19,15">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Name="TB_Question" Text="Choose Answer " Margin="0,0,25,0" HorizontalAlignment="Right" FontWeight="Bold" FontSize="22" FontFamily="Verdana" RenderTransformOrigin="0.5,0.5" />
<TextBlock Name="TB_EnWord" Text="" Margin="90,0,15,0" HorizontalAlignment="Left" FontWeight="Bold" FontSize="22" FontFamily="Verdana" RenderTransformOrigin="0.5,0.5" TextAlignment="Right" />
<StackPanel Grid.Row="1" Margin="5,22,0,0">
<ListView Name="LV_Options" SelectionChanged="LV_Options_SelectionChanged">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="6">
<StackPanel VerticalAlignment="Top" Margin="10,0,0,0">
<TextBlock Name="TB_AMean1" Text="{Binding AMean1}" TextWrapping="Wrap"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
<Button Name="Btn_Answer" Content="Ansewr" HorizontalAlignment="Left" Grid.Row="1" VerticalAlignment="Bottom" Click="Btn_Answer_Click"/>
My application is a quiz application that offer 4 choices/options as answers for each question, and when user select a true answer, I want to highlight the true answer(true choice) by make its background to green, and if the user selected wrong answer/option I want to make the background of that answer (a specific List View item) with red.
Any help please ?
You're not going to be able to access an element inside a data template like that. Instead, leverage the binding to a view model to set the color and other view-related properties. First, create a wrapper view model for your data class:
public class MyTBLViewModel : INotifyPropertyChanged
{
public MyTBL Entity
{
get { return _entity; }
}
private readonly MyTBL _entity;
public Brush Highlight
{
get { return _brush; }
set
{
_brush = value;
RaisePropertyChanged("Highlight");
}
}
private Brush _highlight;
public double ItemFontSize
{
get { return _itemFontSize; }
set
{
_itemFontSize = value;
RaisePropertyChanged("ItemFontSize");
}
}
private Brush _itemFontSize;
public MyTBLViewModel(MyTBL entity)
{
_entity = entity;
_highlight = new SolidColorBrush(Colors.Transparent);
_itemFontSize = 12;
}
public event PropertyChangedEventArgs PropertyChanged;
protected void RaisePropertyChanged(string propName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propName));
}
}
Use this as your ItemsSource:
List<MyTBLViewModel> t_list = db1.GetTable("SELECT * FROM MyTBL LIMIT 4 ORDER BY RANDOM() ;")
.AsEnumerable().Select(entity => new MyTBLViewModel(entity)).ToList();
Now in your view, bind the view elements to "Highlight" and "ItemFontSize", and to any other properties you like:
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="6" Background="{Binding Highlight}">
<StackPanel VerticalAlignment="Top" Margin="10,0,0,0">
<TextBlock Name="TB_AMean1" Text="{Binding Entity.AMean1}" TextWrapping="Wrap"
FontSize="{Binding ItemFontSize}"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
Finally, you can get the data item from the SelectionChangedEventArgs -- use it to update your view-related properties:
private void LV_Options_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
foreach (var item in e.AddedItems.OfType<MyTBLViewModel>())
{
item.Highlight = new SolidColorBrush(Color.LightSteelBlue);
item.ItemFontSize = 17;
}
foreach (var item in e.RemovedItems.OfType<MyTBLViewModel>())
{
item.Highlight = new SolidColorBrush(Colors.Transparent);
item.ItemFontSize = 12;
}
}
var item = LV_Options.Items.ElementAt(3);
This line is incorrect. It will not return you a TextBlock. I don't know what a .BackColor is, and it should not compile. The Items property in a ListView will return you a list of ListViewItems. If you want to access the inside element from a ListViewItem, you'll need to access the ContentTemplateRoot property.
Do not use var ever. It lets you assume that you know the type, whereas if you explicitly typed the declaration you would realize you're doing it wrong.
MyTBL wrd = lv1.SelectedItem as MyTBL;
if (wrd == null)
return;
TextBlock tb = lv1.FindName("TB_AMean1") as TextBlock;
What is a MyTBL type? FindName is only available to framework DependencyObjects so I'm assuming it's a user control? You have to provide a lot more code to show us what you're doing and what you're setting the ListView's ItemsSource and ItemTemplate with and what these errors are and how you have 2 breaking debug errors at once and what the error messages are.
Comprehending runtime error messages is a huge part of being a good developer.

C# WPF Game advice

I want to create a game, where the word is given, but there's one letter missing and you need to choose from one of the letters given below. Being a beginner with C#, I find very difficult to make this work. Right now, I have a word class, which has WordFull, LetterA, LetterB, LetterC, index (where I need to put the letter in) and a CorrectLetter. Then, I load this word object, where I put letter one by one in textboxes and if letter's index in the word (h[e]llo = 1) is equal to the current letter's index property (index = 1), then it displays blank underlined textbox. When you click on that letter, then it checks whether that letter is correct with CorrectLetter property and that's the place where I'm stuck. I want to put that letter in place of empty textbox. But how do I choose it? I think I'm doing something wrong.
TL;DR
I want to make a letter game and I need an advice how to do it.
My XAML grid:
<TabItem Name="zaisti" Header="Vykdyti" IsSelected="True">
<Grid Name="Grid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="7*"/>
<RowDefinition Height="2*"/>
</Grid.RowDefinitions>
<Viewbox Grid.Row="0" Grid.Column="0">
<StackPanel Name="letters" Orientation="Horizontal">
</StackPanel>
</Viewbox>
<Image Grid.Row="0" Grid.Column="1" Name="img" Margin="10" Source="pack://siteoforigin:,,,/pic.jpg"/>
<Grid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Button.Click="Grid_Click">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Margin="10">
<Button.Content>
<Viewbox>
<Label Name="Option1" Content="{Binding LetterA}"></Label>
</Viewbox>
</Button.Content>
</Button>
<Button Grid.Column="1" Margin="10">
<Button.Content>
<Viewbox>
<Label Name="Option2" Content="{Binding LetterB}"></Label>
</Viewbox>
</Button.Content>
</Button>
<Button Grid.Column="2" Margin="10">
<Button.Content>
<Viewbox>
<Label Name="Option3" Content="{Binding LetterC}"></Label>
</Viewbox>
</Button.Content>
</Button>
</Grid>
Code behind:
public partial class MainWindow : Window
{
List<Word> Words = new List<Word>()
{
... data ...
};
int index = 0;
public MainWindow()
{
InitializeComponent();
pradzia.IsSelected = true;
zaisti.IsEnabled = false;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
zaisti.IsSelected = true;
zaisti.IsEnabled = true;
letters.Children.Clear();
LoadWord(index);
this.DataContext = Words[index];
}
private void Grid_Click(object sender, RoutedEventArgs e)
{
if (index == Words.Count() - 1) return;
MessageBox.Show((((e.Source as Button).Content as Viewbox).Child as Label).Content.ToString());
if ((((e.Source as Button).Content as Viewbox).Child as Label).Content.ToString() == Words[index].LetterCorrect)
{
letters.Children.Clear();
LoadWord(++index);
this.DataContext = Words[index];
}
}
private void LoadWord(int i)
{
int a = 0;
foreach (char l in Words[i].WordFull)
{
TextBlock letter = new TextBlock();
letter.Foreground = new SolidColorBrush(Colors.Gray);
letter.Text = l.ToString();
letter.Margin = new Thickness(2);
if (Words[i].index == a)
{
letter.Text = ((char)160).ToString() + ((char)160).ToString();
// Create an underline text decoration. Default is underline.
TextDecoration myUnderline = new TextDecoration();
// Create a solid color brush pen for the text decoration.
myUnderline.Pen = new Pen(Brushes.Red, 1);
myUnderline.PenThicknessUnit = TextDecorationUnit.FontRecommended;
// Set the underline decoration to a TextDecorationCollection and add it to the text block.
TextDecorationCollection myCollection = new TextDecorationCollection();
myCollection.Add(myUnderline);
letter.TextDecorations = myCollection;
}
a++;
letters.Children.Add(letter);
}
}
}
Word class:
class Word
{
public string WordFull { get; set; }
public string LetterA { get; set; }
public string LetterB { get; set; }
public string LetterC { get; set; }
public string LetterCorrect { get; set; }
public int index { get; set; }
}
Based on what I'm seeing, I would do the following
move the creation of the individual letter elements (including the underline) into their own methods that return the component to display.
Then when the player picks the correct letter,
find the underline element,
remove it from the letters visual control,
and replace it with the the correct letter element.
edit - based on comment
There are several ways of getting to the elements in the Children collection. If you know the actual element,
letters.Children.Remove(element);
will allow you to remove the specified element, or
letters.Children[index];
will work if you know the index.

WPF selected value , displaymember path inconsistency with listbox and combo box

I have a stored procedure called DropDownIndividuals() which was created using LINQ.
The stored procedure returns FullName and Case_Number. I want to set the SelectedValuePath equal to the Case_Number column in my stored procedure. This is how I did it for a listbox and it works.
private void listBox1_Loaded(object sender, RoutedEventArgs e){
using (ToolboxDataContext toolboxDB = new ToolboxDataContext())//this is linq in action
{
var x = toolboxDB.DropDownIndividuals().ToList();//convert to a list
listBox1.ItemsSource = x; //bind the data
listBox1.SelectedValuePath = "Case_Number";
listBox1.DisplayMemberPath = "FullName";
Console.WriteLine(listBox1.SelectedValue.ToString());
//Result:it shows the case number of the person the user picks.
}
}
Now I do the same thing for a dropdown combobox AND IT DOES NOT WORK.
private void individualDropDown_Loaded(object sender, RoutedEventArgs e)
{
using (ToolboxDataContext toolbox = new ToolboxDataContext())
{
var individualDropDownBox = toolbox.DropDownIndividuals().ToList();
individualDropDown.ItemsSource = individualDropDownBox;
individualDropDown.DisplayMemberPath = "FullName";
individualDropDown.SelectedValuePath = "Case_Number";
Console.WriteLine(individualDropDown.SelectedValue.ToString());
}
}
Why? How can I fix this?
Why so chaotic? You do not even set properties in the same order, this is equivalent:
<Grid Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ListBox Grid.Row="0" Grid.Column="0"
Name="lbData" ItemsSource="{Binding DpData}"
DisplayMemberPath="Name"
SelectedValuePath="Id"/>
<TextBlock Grid.Row="1" Grid.Column="0"
Text="{Binding ElementName=lbData, Path=SelectedValue}"/>
<ComboBox Grid.Row="0" Grid.Column="1" VerticalAlignment="Top"
Name="cbData" ItemsSource="{Binding DpData}"
DisplayMemberPath="Name"
SelectedValuePath="Id"/>
<TextBlock Grid.Row="1" Grid.Column="1"
Text="{Binding ElementName=cbData, Path=SelectedValue}"/>
</Grid>
...and it displays the same ID as expected.
Edit: At startup the selected value of both controls is null by the way.
You are correct, there is an inconsistency of sorts between the way that SelectedValue is treated for ListBox and ComboBox. For ListBox, upon load, if it has the focus, the SelectedValue will correspond to the first item in the data source. For ComboBox even if it has the focus and a data source supplies items, the default SelectedValue will be unset during the Loaded event handler.
This behavior is by design. To make the ComboBox behave like the ListBox set ComboBox.SelectedIndex to "0" where you define the ComboBox in the XAML.
Try this:
MetroAreaList metroAreaList = _presenter.GetMetroArea();
foreach (MetroArea metroArea in metroAreaList) {
lstMetroArea.DisplayMemberPath = "Name";
lstMetroArea.SelectedValuePath = "ID";
lstMetroArea.Items.Add(metroArea);
}
It is working....
Your class should be public:
public class Place
{
public string Name { get; set; }
public string Id { get; set; }
}
foreach (var y in Lists)
{
listBox1.DisplayMemberPath = "Name";
listBox1.SelectedValuePath = "Id";
// Console.WriteLine(y.Case_Number.ToString());
listBox1.Items.Add(y);
}

Categories