Items doesn't display in combobox wpf - wpf

I have ComboBox
<ComboBox Grid.Column="1" Grid.Row="1" Margin="3" Name="cmbPlayer1" IsEditable="true"></ComboBox>
and I initialize my Combobox with data from database. I have procedure which initialize this and then I call this procedure.
Public Sub InitComboxesPlayers(cmbPlayer As ComboBox)
Using myDataReader As SqlDataReader = GetSqlFunctions.GetExecutedDataReaderFromSql(
"SELECT PLAYER_ID, " &
" PLAYER_NICKNAME, " &
" PLAYER_FIRSTNAME, " &
" PLAYER_LASTNAME " &
" FROM PLAYERS ", myConnection)
While myDataReader.Read
Dim myNewPlayer As New Players
With myNewPlayer
.Player_ID = CInt(myDataReader("PLAYER_ID"))
.Nickname = myDataReader("PLAYER_NICKNAME").ToString.Trim
.Firstname = myDataReader("PLAYER_FIRSTNAME").ToString.Trim
.Lastname = myDataReader("PLAYER_LASTNAME").ToString.Trim
End With
lstOfPlayers.Add(myNewPlayer)
End While
End Using
cmbPlayer.ItemsSource = lstOfPlayers
cmbPlayer.DataContext = lstOfPlayers
cmbPlayer.DisplayMemberPath = "PLAYER_NICKNAME"
cmbPlayer.SelectedValuePath = "PLAYER_ID"
End Sub
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
InitComboxesPlayers(cmbPlayer1)
End Sub
So, my values does not display in combobox. But you can see on the picture that values are in Combobox, because it's not empty. What is wrong?

Try this... you need to assign the property names from your class, not the column names from your sql...
cmbPlayer.DisplayMemberPath = "Nickname"
cmbPlayer.SelectedValuePath = "Player_ID"

Two Approaches :-
1) Update your code to use the property instead of DataBase Column names :-
cmbPlayer.DisplayMemberPath = "Nickname "
2) You can create an Item template for your combo box, so you don't need to set the DisplayMemberPath in your Code.
<ComboBox Grid.Column="1" Grid.Row="1" Margin="3" Name="cmbPlayer1" IsEditable="true">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text={Binding Nickname}
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>

Related

Hierarchical Code First EF Binding to WPF Treeview... Impossible

In the past, I had to resort to using DataSets and DataTables, as doing it with Binding still eludes me...
Top Level: I created a series of classes in VB 2012, annotated them, and crated the EF model in EF6 using Code First. The idea is to represent router configs, with sub-sections of the config being children to the major sections. Very simple idea.
Rationale: With a simple WPF Treeview, illustrate the config sections and subsections as they appear (logically) in the router.
I have started very simply with these classes, intending later to use 2-way binding to update each way, etc. Here are the first 2 top classes (snipped for brevity):
This is standard EF CodeFirst fare, and the DBContext is laid out by EF as you'd expect. This is the layout of the top 2 level classes (Access_Group & Access_List):
...and all is well in EF-Land...
Because it will likely be important, here is the actual Access_Group class:
Public Class Access_Group
Inherits EntityTypeConfiguration(Of Access_Group)
Implements IAccess_Group
<Key>
Public Property Access_GroupID As Integer Implements IAccess_Group.Access_GroupID
Public Property Name As String Implements IAccess_Group.Name
Public Property LastUpdated As Date Implements IAccess_Group.LastUpdated
Public Property Active As Boolean Implements IAccess_Group.Active
'------------------------------------------------------------------
Public Property Access_Lists As ObservableCollection(Of Access_List) Implements IAccess_Group.Access_Lists
Public Sub New()
Me.Access_Lists = New ObservableCollection(Of Access_List)
End Sub
End Class
There are many event-based components that I have not added yet, because I just want the basics to work (display hierarchically in a Treeview) before I add the bells & whistles...
So this is how the classes are created in code, that populated the database (SQL 2012) in the first place:
[Window Class contd.]
Private Sub AddData()
Try
ctx = New entitiesContext
Dim d As Date = Now
'--------------------------------
Dim al As New Access_List
' lower classes not needed to be shown...
With al
.Active = True
.Checked = True
.LastUpdated = d
.Name = "some access-list at " & d.ToLongTimeString
End With
'--------------------------------
Dim ag As Access_Group = New Access_Group
With ag
.Access_Lists.Add(al)
.Active = True
.LastUpdated = d
.Name = "some access-group at " & d.ToLongTimeString
End With
'
ctx.Access_Groups.Add(ag)
'
Dim i As Integer = ctx.SaveChanges()
Console.WriteLine("Seed complete! -> " & i)
Catch ex As Exception
Dim exText As String = "Seed Failed "
Console.WriteLine(exText & "(Message): " & ex.Message)
Console.WriteLine(exText & "(ToString): " & ex.ToString)
Console.WriteLine(exText & "(StackTrace): " & ex.StackTrace)
Console.WriteLine("EntityValidationErrors: ")
For Each eve As System.Data.Entity.Validation.DbEntityValidationResult In ctx.GetValidationErrors()
Console.WriteLine("eve: OK? " & eve.IsValid & " - " & eve.Entry.ToString)
For Each devr As System.Data.Entity.Validation.DbValidationError In eve.ValidationErrors
Console.WriteLine("devr invalid property: " & devr.PropertyName)
Console.WriteLine("devr error message : " & devr.ErrorMessage)
Next
Next
End Try
End Sub
You see Access_List referred to above as the 2nd level down, and this is that class:
Public Class Access_List
Inherits EntityTypeConfiguration(Of Access_Group)
Implements toag.entities.IAccess_List
<Key>
Public Property Access_ListID As Integer Implements IAccess_List.Access_ListID
Public Property Name As String Implements IAccess_List.Name
Public Property LastUpdated As Date Implements IAccess_List.LastUpdated
Public Property Active As Boolean Implements IAccess_List.Active
Public Property Checked As Boolean Implements IAccess_List.Checked
Public Property Object_Groups As ObservableCollection(Of Object_Group) Implements IAccess_List.Object_Groups
Public Sub New()
Me.Object_Groups = New ObservableCollection(Of Object_Group)
End Sub
End Class
If I can figure out how to get these 2 classes to behave, I can template & get the rest to do so as well...
I have tried HUNDREDS of code & XAML combinations, so I'll settle down with one that at least shows something on the Treeview:
<TreeView Grid.Column="0"
x:Name="ACLTreeView"
HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch"
ItemsSource="{Binding Access_Group}">
</TreeView>
When this XAML is combined with this code-behind:
Public Class ConfigWindow
Property ctx As entitiesContext
Public Access_Group_List As IEnumerable(Of Access_Group)
Sub New()
' This call is required by the designer.
InitializeComponent()
Startup()
End Sub
Public Sub Startup()
Try
ctx = New vASAContext
Me.Access_Group_List = From ag In ctx.Access_Groups Select ag
Me.ACLTreeView.ItemsSource = Access_Group_List.ToList
Catch ex As Exception
Debug.Print("ex: " & ex.Message)
End Try
End Sub
End Class
Will yield the following:
(sorry about having to obfuscate the namespace...) Which is fine, as there is no HierarchicalTemplate or even TreeViewItem in XAML.
Here is modified XAML:
...which will show the Name property of the Access_Group entity instead of it's class name [can't add a screenshot of it when editing a post, so you may have to trust me on this one! :)]
But there is another sub in the Window class that points to a problem with the hierarchy possibly not being recognized. Could it be that I've been trying examples that were correct, and my EF classes weren't set up properly? This sub should show all the elements and their children:
Public Sub PrintDebug(TheList As IEnumerable(Of Access_Group))
For Each ag As Access_Group In TheList
Console.WriteLine("=======================================")
Console.WriteLine("ag: " & ag.Name & " has " & ag.Access_Lists.Count & " Access_List entries")
For Each al As Access_List In ag.Access_Lists
Console.WriteLine("ag -> al: " & al.Name & " has " & al.Object_Groups.Count & " Object_Group entries")
For Each og As Object_Group In al.Object_Groups
Console.WriteLine("ag -> al -> og: " & og.Name & " has " & og.Network_Objects.Count & " Network_Object entries")
'...
Next
Next
Console.WriteLine("=======================================")
Next
End Sub
But this is what that debug class puts out:
=======================================
ag: some access-group at 5:00:49 PM has 0 Access_List entries
=======================================
=======================================
ag: some access-group at 5:08:56 PM has 0 Access_List entries
=======================================
=======================================
ag: some access-group at 5:09:14 PM has 0 Access_List entries
=======================================
=======================================
ag: some access-group at 5:12:31 PM has 0 Access_List entries
=======================================
[...]
? Does this mean that my Treeview doesn't have a chance? But, but... the data is correct in the DB:
All of those keys were populated by EF when I used the above code (only saving the top level class (Access_Group) after populating it's ObservableCollections...)
???
I've tried every combination of HierarchicalTemplate, in grid/window resources, nested, etc. And I'm back to square 1 after 3 days... :) Yes, all kinds of LINQ queries, too... And now I'm contemplating SQL (GASP) or JOINs in either LINQ/SQL, but then I may as well go all the way back to DataSets & DataTables if I'm ready to really give up...
Any help appreciated... I just can't move on until I can get these entities to bind correctly...
I've created sample object model of your entities (AccessGroup, AccessList and ObjectGroup) and this code might help you:
Code-behind
Imports System.Collections.ObjectModel
Class MainWindow
Property AccessGroups As New ObservableCollection(Of AccessGroup)
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Me.DataContext = Me
Dim ag1 = New AccessGroup With {.Name = "AG1"}
Dim ag2 = New AccessGroup With {.Name = "AG2"}
Dim al1 = New AccessList With {.Name = "AL1"}
Dim al2 = New AccessList With {.Name = "AL2"}
Dim al3 = New AccessList With {.Name = "AL3"}
Dim og1 = New ObjectGroup With {.Name = "OG1"}
Dim og2 = New ObjectGroup With {.Name = "OG2"}
al1.ObjectGroups = New List(Of ObjectGroup) From {og1}
al2.ObjectGroups = New List(Of ObjectGroup) From {og2}
ag1.AccessList = New List(Of AccessList) From {al1, al2}
ag2.AccessList = New List(Of AccessList) From {al3}
AccessGroups.Add(ag1)
AccessGroups.Add(ag2)
End Sub
End Class
Public Class AccessGroup
Property Name As String
Property AccessList As IEnumerable(Of AccessList)
End Class
Public Class AccessList
Property Name As String
Property ObjectGroups As IEnumerable(Of ObjectGroup)
End Class
Public Class ObjectGroup
Property Name As String
End Class
XAML
<TreeView ItemsSource="{Binding AccessGroups}">
<!-- AccessGroup template -->
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding AccessList}">
<TextBlock Text="{Binding Name}" />
<!-- AccessList template -->
<HierarchicalDataTemplate.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding ObjectGroups}">
<TextBlock Text="{Binding Name}" />
<!-- ObjectGroup template -->
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
On the picture bellow you can see the result

DAL Generator: How to get Grid Checkbox?

I am building a WPF D.A.L. generator.
In my main page, I have a DataGrid populated with a list of the tables in my database.
I also have an extra checkbox column called ShouldInclude? I intend to use this to determine whether or not the table should be included in the generation... yes if checked, no if un-checked.
Because I am populating the DataGrid's ItemSource with a strongly typed list of some basic info TableName, Schema, Columns, I am now finding myself at a loss as to how I can get the checked value of the checkbox so I can make that determination on whether to include it or not.
Here are my functions that build out my table typing class code files:
Private Sub GenerateTyping(ByVal _DG As DataGrid)
For Each i As TableTyping In _DG.Items
'check if should be generated
Dim _TString As String = String.Empty
Using _sr As New StreamReader(Common.GetPath() & "Class Templates\CSharp\Typing\XXX_Typing.txt")
_TString = _sr.ReadToEnd()
_sr.Close()
End Using
Dim _FN As String = i.Name & "_Typing.cs"
Dim _Props As New StringBuilder()
Dim _CL As List(Of ColumnTyping) = i.Columns
For Each col In _CL
With _Props
Dim _PropStr As String = "public " & Common.GetClrType(col.Type) & " " & col.Name & " { get; set; }"
.AppendLine(" " & _PropStr)
End With
Next
'Write the new class files
_TString = _TString.Replace("##TABLENAME##", If(i.Schema.Length > 0, i.Schema & "_", "") & i.Name).Replace("##THE_PROPERTIES##", _Props.ToString())
If Not Directory.Exists(FilePath & "\Typing\") Then
Directory.CreateDirectory(FilePath & "\Typing\")
End If
Using _sw As New StreamWriter(FilePath & "\Typing\" & If(i.Schema.Length > 0, i.Schema & "_", "") & i.Name & "_Typing.cs", False)
_sw.Write(_TString)
_sw.Close()
End Using
_TString = String.Empty
_Props.Clear()
Next
End Sub
Partial Public Class TableTyping
Public Property ID As Integer
Public Property Name As String
Public Property Schema As String
Public Property Columns As List(Of ColumnTyping)
End Class
Partial Public Class ColumnTyping
Public Property ID As Integer
Public Property Name As String
Public Property Type As SqlDataType
Public Property Length As Integer
Public Property DefaultValue As String
Public Property Precision As Integer
Public Property Scale As Integer
End Class
My datagrid simply consists of 3 columns. Include?, Table Schema, Table Name, which is populated via:
<DataGrid EnableRowVirtualization="True" Name="dgTables" IsReadOnly="True" AutoGenerateColumns="False" FontFamily="Calibri" FontSize="14" IsEnabled="False">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Include?">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox Tag="{Binding ID}" HorizontalAlignment="Center" VerticalAlignment="Center" IsChecked="True" Name="ckTblInclude" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Binding="{Binding Schema}" Header="Schema"/>
<DataGridTextColumn Binding="{Binding Name}" Header="Name"/>
</DataGrid.Columns>
</DataGrid>
AND:
_tg.ItemsSource = _Table
Private Sub GrabTables()
Dim _Db As Database = Srv.Databases(DBName)
Dim _Tbls As TableCollection = _Db.Tables
Dim _tct As Integer = _Tbls.Count
Dim _i As Integer = 0
For i = 0 To _tct - 1
If Not _Tbls(i).IsSystemObject Then
_i += 1
_Tables.Add(New TableTyping() With {
.ID = _i,
.Name = _Tbls(i).Name,
.Schema = _Tbls(i).Schema,
.Columns = ProcessColumns(_Tbls(i).Columns)})
End If
Next
_TCount = _Tables.Count
End Sub
_Tables is a List(of TableTyping)
How can I do the Include? check inside the GenerateTyping procedure?
I had to change my checkbox template to the following:
<CheckBox Tag="{Binding ID}" HorizontalAlignment="Center" VerticalAlignment="Center" IsChecked="{Binding Include, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Name="ckTblInclude" />
And change the _Tables list to populate via:
Private Sub GrabTables()
Dim _Db As Database = Srv.Databases(DBName)
Dim _Tbls As TableCollection = _Db.Tables
Dim _tct As Integer = _Tbls.Count
Dim _i As Integer = 0
For i = 0 To _tct - 1
If Not _Tbls(i).IsSystemObject Then
_i += 1
_Tables.Add(New TableTyping() With {
.ID = _i,
.Name = _Tbls(i).Name,
.Schema = _Tbls(i).Schema,
.Columns = ProcessColumns(_Tbls(i).Columns),
.Include = True})
End If
Next
_TCount = _Tables.Count
End Sub

Casting to a type dynamically in VB

I've been hunting through stackoverflow for a while to answer this.
I've got a Listview who's items are Listviews whose children are actually a list(of string) that is a member of the parent listviewitem.
Drag and drop functionality is the goal. However this is proving hard for a variety of reasons, one of which is casting. I need to get the type before I do a direct cast to make it work - at least I think that will get me over one problem.
However I can't get this syntax to even begin to work, so I'll start here:
Dim itemType = listView.ItemContainerGenerator.ItemFromContainer(listViewItem)
Dim g As Type = GetType(itemtype)
This is the entire drag n drop implementation I'm trying:
Dim startpoint As Point
Public Sub List_PreviewMouseLeftButtonDown(sender As Object, e As MouseEventArgs)
' Store the mouse position
startpoint = e.GetPosition(Nothing)
End Sub
Private Sub List_MouseMove(sender As Object, e As MouseEventArgs)
Dim mousePos As Point = e.GetPosition(Nothing)
Dim diff As Vector = startpoint - mousePos
If e.LeftButton = MouseButtonState.Pressed And Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance Or Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance Then
Dim listView As ListView = DirectCast(sender, ListView)
Dim listViewItem As ListViewItem = FindAncestor(Of ListViewItem)(DirectCast(e.OriginalSource, DependencyObject))
Dim itemType = listView.ItemContainerGenerator.ItemFromContainer(listViewItem)
Dim g As Type = GetType(itemtype)
Dim item As String = DirectCast(listView.ItemContainerGenerator.ItemFromContainer(listViewItem), String)
Dim dragData As New DataObject("myFormat", item)
DragDrop.DoDragDrop(listViewItem, dragData, DragDropEffects.Move)
End If
End Sub
Private Shared Function FindAncestor(Of T As DependencyObject)(current As DependencyObject) As T
Do
If TypeOf current Is T Then
Return DirectCast(current, T)
End If
current = VisualTreeHelper.GetParent(current)
Loop While current IsNot Nothing
Return Nothing
End Function
Private Sub DropList_DragEnter(sender As Object, e As DragEventArgs)
If Not e.Data.GetDataPresent("myFormat") OrElse sender = e.Source Then
e.Effects = DragDropEffects.None
End If
End Sub
Private Sub DropList_Drop(sender As Object, e As DragEventArgs)
If e.Data.GetDataPresent("myFormat") Then
Dim contact As String = TryCast(e.Data.GetData("myFormat"), String)
Dim listView As ListView = TryCast(sender, ListView)
listView.Items.Add(contact)
End If
End Sub
Here is the nested listView:
<!--DataContext="{StaticResource RcpdInsertViewSource}" This is a collectionviewsource.
RCPDInsert has a list(of string) member that is created from a single string property
and whose order needs to be alterable.
Eg rcpdInsert.template="[stuff] [more stuff]" so rcpdInsert.templateList = list(of String) from template.split("] [") -->
<ListView Grid.Column="1" Grid.Row="1" ItemsSource="{Binding}"
PreviewMouseLeftButtonDown="List_PreviewMouseLeftButtonDown"
PreviewMouseMove="List_MouseMove"
Drop="DropList_Drop"
DragEnter="DropList_DragEnter"
AllowDrop="True">
<ListView.ItemTemplate>
<DataTemplate>
<DockPanel>
<TextBox Text="{Binding Path=cpID}"></TextBox>
<TextBox Text="{Binding Path=fieldRef}"></TextBox>
<ListView ItemsSource="{Binding Path=InsertsList}" >
<ListView.ItemTemplate>
<DataTemplate DataType="DataClasses1:RcpdInsert.template" >
<StackPanel Orientation="Horizontal" Grid.Row="0">
<TextBlock Text="{Binding}" Margin="5" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</DockPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Goal: Drag and drop reordering of child listviews, ideally being able to pull individual items from one child listView to another. When saved, the code behind will actually concat the strings back together and update the template member.
For context here are the relevant members of RcpdInsert:
Sub SetupInsertList()
_insertsList = template.Split(" ").ToList()
For Each item In InsertsList
Dim t = item
RcpdList.Add(RcpdSet.RpcdListShared.Where(Function(x) x.insertID = t).ToList())
Next
End Sub
Public Property RcpdList As New List(Of List(Of Rcpd))
Private Property _insertsList As New List(Of String)
Public Property InsertsList As List(Of String)
Get
If _insertsList.Count = 0 Then setupInsertList()
Return _insertsList
End Get
Set(value As List(Of String))
Dim combine As String = value.Aggregate("", Function(current, i) current + (i & " "))
template = combine
End Set
End Property
The casting is one issue with this, I'm hoping being able to do this part means that the others will be easier to resolve.
Thanks in advance to anyone who can help :)

Binding ListView Throws Window must be the root of the tree. Cannot add Window as a child of Visual

I am attempting to bind a ObservableCollection to a ListView but when I attempt to debug the program VS2010 is throwing the exception "Window must be the root of the tree. Cannot add Window as a child of Visual"
If I was to remove the attempted ItemsSource binding the WPF window opens (obviously without any data in the listView). I have create a Sub in my codebehind that parses an XML file and adds values to the ObservableCollection, I then bind the ListView.
I have stepped through the code, and the error appears to be in the XAML as the Sub completes without error, the program errors after the CodeBehind has completed, everytime.
My XAML file is as follows:
<Window x:Class="test_ListView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="test_ListView" Height="300" Width="300">
<Grid>
<ListView Height="105" HorizontalAlignment="Left" Name="lst_EmergencyContacts" VerticalAlignment="Top" Width="478">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" Width="160" />
<GridViewColumn DisplayMemberBinding="{Binding emContactsNumber}" Header="Number" Width="70" />
<GridViewColumn DisplayMemberBinding="{Binding emContactsPhoneCoverage}" Header="Phone Coverage" Width="95" />
<GridViewColumn DisplayMemberBinding="{Binding distListPhone}" Header="Distance" Width="60" />
<GridViewColumn Header="More" Width="60" />
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
While I believe the error is within the XAML, I will include the CodeBehind details, just in case (as the program will run without the error if the Sub isnt called that binds the ListView).
Public Property emContactsName() As String
Get
Return em_Name
End Get
Set(ByVal value As String)
em_Name = value
End Set
End Property
Private em_Name As String
Public Property emContactsNumber() As String
Get
Return em_Number
End Get
Set(ByVal value As String)
em_Number = value
End Set
End Property
Private em_Number As String
Public Property emContacts27Mhz() As String
Get
Return em_27Mhz
End Get
Set(ByVal value As String)
em_27Mhz = value
End Set
End Property
Private em_27Mhz As String
Public Property emContactsUhf() As String
Get
Return em_Uhf
End Get
Set(ByVal value As String)
em_Uhf = value
End Set
End Property
Private em_Uhf As String
Public Property emContactsVhf() As String
Get
Return em_Vhf
End Get
Set(ByVal value As String)
em_Vhf = value
End Set
End Property
Private em_Vhf As String
Public Property IsSelected() As Boolean
Get
Return m_IsSelected
End Get
Set(ByVal value As Boolean)
m_IsSelected = value
End Set
End Property
Private m_IsSelected As Boolean
Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
getEmergencyContactsData("\", "EmergencyContacts.xml")
End Sub
Private Sub getEmergencyContactsData(ByVal docPath As String, ByVal docName As String)
Try
Dim xDoc As XmlDocument = New XmlDocument
Dim nList As XmlNodeList
Dim node As XmlNode
xDoc.Load(docPath + docName)
nList = xDoc.SelectNodes("/items/item")
Dim emergencyContactsCollection As New ObservableCollection(Of test_googleLookup)()
For Each node In nList
Dim eID = node.Attributes.GetNamedItem("id").Value
Dim eName = node.ChildNodes.Item(0).InnerText
Dim eNumber = node.ChildNodes.Item(1).InnerText
Dim eRadio27Mhz = node.ChildNodes.Item(2).InnerText
Dim eRadioUhf = node.ChildNodes.Item(3).InnerText
Dim eRadioVhf = node.ChildNodes.Item(4).InnerText
emergencyContactsCollection.Add(New test_googleLookup() With {.emContactsName = eName, .emContactsNumber = eNumber, .emContacts27Mhz = eRadio27Mhz, .emContactsUhf = eRadioUhf, .emContactsVhf = eRadioVhf, .IsSelected = 0})
Next
' Add to resources
Resources("emergencyContactsCollection") = emergencyContactsCollection
lst_EmergencyContacts.ItemsSource = emergencyContactsCollection
Catch
End Try
End Sub
I can see when stepping through the debug that the XML file is being correctly parsed and the values being added to the ObservableCollection.
If anyone can provide any assistance it would be greatly appreciated.
Thanks.
Try changing emergencyContactsCollection into a public property (ie.,EmergencyContacts) of test_ListView. Set the DataContext of lst_EmergencyContacts to be EmergencyContactsCollection.
<Window x:Class="test_ListView" ... DataContext="{Binding RelativeSource={RelativeSource Self}}">
<ListView Name="lst_EmergencyContacts" ... DataContext="{Binding Path=EmergencyContacts}">
Managing your data binding in this way often makes things much easier. Even better would be to separate out the data bound Properties to their own ViewModel.
I ended up using ListBoxes, below is the code I used, in case anyone is interested:
<ListBox Grid.Row="1" Grid.Column="0" Grid.RowSpan="4" Grid.ColumnSpan="3" HorizontalAlignment="Stretch" ItemsSource="{DynamicResource emergencyContactsCollection}" Name="lst_emergencyServices" VerticalAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding emerContIsSelected, Mode=TwoWay}" />
<TextBlock Text="{Binding emerContName}" />
<TextBlock Text="{Binding emerContNumber}" />
<TextBlock Text="{Binding emerContRadio27mhz}" />
<TextBlock Text="{Binding emerContRadioUhf}" />
<TextBlock Text="{Binding emerContRadioVhf}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Thank you for your time and assistance.
Matt

How to add items rows to a listview WPF and VB.net

Im getting crazy with it. It is so easy in windows form, but in wpf it seems to be different.
Every example i find is in C# and i cant addapt it.
Well, this is the code i have. Atm, i have just defined the columns:
'diseño de las columnas
Dim item As ListViewItem = New ListViewItem
Dim Mi_Lista As GridView = New GridView
Mi_Lista.AllowsColumnReorder = True
Dim cine As New GridViewColumn()
Dim Si3d As New GridViewColumn
cine.Header = "Cine"
cine.DisplayMemberBinding = New Binding("Cine")
Si3d.DisplayMemberBinding = New Binding("si3D")
cine.Width = 140
Si3d.Header = "3D"
Si3d.Width = 50
Mi_Lista.Columns.Add(cine)
Mi_Lista.Columns.Add(Si3d)
Thanks in advance.
There are two ways to do this:
Add ListViewItems to the ListView.Items property. This is the WinForms way but is not idiomatic in WPF.
Set the ListView.ItemsSource property. WPF will then create a row for each entry in the ItemsSource collection. You will not need to Dim ListViewItem objects yourself in this case. This is idiomatic WPF.
To do option 2, write something like this:
Dim data As ObservableCollection(Of Something) = New ObservableCollection(Of Something)
' Populate the collection
lv.ItemsSource = data
Note that here lv is your ListView, not your GridView. Also you would normally define your ListView and columns in XAML rather than code, e.g.
<ListView Name="lv">
<ListView.View>
<GridView>
<GridViewColumn Header="Cine"
DisplayMemberBinding="{Binding Cine}"
Width="140" />
</GridView>
</ListView.View>
</ListView>
Yeah, i got it some days ago, thanks.
For future users:
Public Sub LlenarLista(ByVal película As String)
' MessageBox.Show(película)
Dim dtLista As DataTable
Dim dt As DataTable = New DataTable()
Dim connetionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=Cinépolis.mdb"
Dim connection As OleDbConnection = New OleDbConnection(connetionString)
connection.Open()
Dim da As OleDbDataAdapter = New OleDbDataAdapter("SELECT Cines.Nombre as nombre, Películas.Título, Proyecciones.[3D] AS p3d, Cines.web, Cines.Ubicacion as Ubicación, Cines.Parking FROM Películas INNER JOIN (Cines INNER JOIN Proyecciones ON Cines.IdCine = Proyecciones.IDCine) ON Películas.IDPelícula = Proyecciones.IDPelícula WHERE (((Películas.Título)='" & película & "')); ", connection)
da.Fill(dt)
dtLista = dt
lvCines.DataContext = dtLista
lvCines.SetBinding(ListView.ItemsSourceProperty, New Binding)
connection.Close()
Y el diseño:
<GridView ColumnHeaderTemplate="{StaticResource estiloCabecera}" >
<GridViewColumn Header="Cine" DisplayMemberBinding="{Binding nombre}" />
<GridViewColumn Header="3D" Width="50" DisplayMemberBinding="{Binding p3d}"/>
<GridViewColumn Header="Web" Width="150" DisplayMemberBinding="{Binding web}"/>
</GridView>
</ListView.View>
</ListView>
Disclaimer: C#
this is the starting point:
http://www.switchonthecode.com/tutorials/wpf-tutorial-using-the-listview-part-1
C# to VB.Net:
http://www.developerfusion.com/tools/convert/csharp-to-vb/

Resources