I have a WPF application I am working on that uses the Entity Framework 4.0 an Observable Collection and a few CollectionViewSources. On my form i have two text boxes i use to filter my data and then display it into a listbox based on what I have filtered it by. What I need to do is to have the user select an item from the listbox and hit a button ("Select") and the information is displayed wiht appropriate collections in a whole new window.
So far I have:
Imports System.Data.Objects
Public Class SearchText
Private db As New CraftingProjectsEntities
Private ProjectsData As ProjectsCollection
Private ProjectViewSource As CollectionViewSource
Private MaterialsViewSource As CollectionViewSource
Private ColoringsViewSource As CollectionViewSource
Private DirectionsViewSource As CollectionViewSource
Private SpecialsViewSource As CollectionViewSource
Private WithEvents ProjectView As ListCollectionView
Private MaterialsView As BindingListCollectionView
Private ColoringsView As BindingListCollectionView
Private SpecialsView As BindingListCollectionView
Private DirectionsView As BindingListCollectionView
Private Sub SearchText_Loaded(sender As Object, e As System.Windows.RoutedEventArgs) Handles Me.Loaded
Dim query = From r In db.Projects
Where r.Materials.Count > 1
Select r
Me.ProjectViewSource = CType(Me.FindResource("ProjectsViewSource"), CollectionViewSource)
Me.DirectionsViewSource = CType(Me.FindResource("DirectionsViewSource"), CollectionViewSource)
Me.ColoringsViewSource = CType(Me.FindResource("ColoringsViewSource"), CollectionViewSource)
Me.SpecialsViewSource = CType(Me.FindResource("SpecialsViewSource"), CollectionViewSource)
Me.MaterialsViewSource = CType(Me.FindResource("MaterialsViewSource"), CollectionViewSource)
Me.ProjectViewSource.Source = Me.ProjectsData
Me.ProjectView = CType(Me.ProjectViewSource.View, ListCollectionView)
Me.DirectionsView = CType(Me.DirectionsViewSource.View, BindingListCollectionView)
Me.ColoringsView = CType(Me.ColoringsViewSource.View, BindingListCollectionView)
Me.MaterialsView = CType(Me.MaterialsViewSource.View, BindingListCollectionView)
Me.SpecialsView = CType(Me.SpecialsViewSource.View, BindingListCollectionView)
MyLists.ItemsSource = ProjectsData
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
Dim query2 As ObjectQuery(Of Project) = Nothing
Dim query = From p In db.Projects
Select p
If TextBox2.Text.Length > 1 And TextBox1.Text.Length > 1 Then
query2 = query.Where(Function(p) p.Materials.Any(Function(m) m.Material1.ToLower().Contains(Me.TextBox1.Text)) And
p.Materials.Any(Function(m) m.Material1.ToLower().Contains(Me.TextBox2.Text)))
ElseIf TextBox2.Text.Length < 1 And TextBox1.Text.Length > 1 Then
query2 = query.Where(Function(p) p.Materials.Any(Function(m) m.Material1.ToLower().Contains(Me.TextBox1.Text)))
Else
MessageBox.Show("What are you looking for?")
Return
End If
Me.ProjectsData = New ProjectsCollection(query2.ToList(), db)
MyLists.ItemsSource = ProjectsData
End Sub
**Works great through here... Below is where i get lost trying to get the selected item to the new window**
Private Sub btnSelect_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles btnSelect.Click
Dim mychoice As New MyChoice
Dim selitem = Me.MyLists.SelectedItem
mychoice.ProjectsData = (selitem)
mychoice.Show()
Me.Close()
End Sub
End Class
Any thoughts on how I could do this or where I could find an example showing the proper way of doing this would be extremely appreciated. Thanks.
Adam
Sorry.... not using MVVM if this helps.
Make your model Project a parameter of the MyChoice window class. Depending on whether it's required for the window, make Project a required or optional parameter of the MyChoice constructor. Set it as the Data Context for your new window's Layout Root, set it as a property of the Window class itself, or put it in the View Model; whichever is appropriate.
Related
I'm posting this after losing my time by searching & got no proper answer.
My requirement is to create a permit system.
There is a tabcontrol on the form & when I click on "New Permit" button (located top of the form above tabcontrol), a new tab should open (named "NEW Permit") with text boxes on it.
Each time "New Permit" button is clicked, same type of tabs to be opened parallely.
When we select a one tab & fill in the text fields & click on "Issue Permit" button (located top of the form above tabcontrol), tab should be closed while saving the data in text fields to a access database with a dedicated permit number.
I have created the form & the "New Permit","Issue Permit" buttons & tabcontrol are on a usercontrol "ucPermit".
I'm struck in creating those dynamic tabs & getting the data on those into a database.
'''''''''' Annex ''''''''''''''''''''''''''''''''''''''
#DonA
I have two panels on the form.
Panel 01 (on left) has buttons "Summary, Permit, LOTO, HotWork".
When each button is clicked respective usercontrol (loaded onto panel 02 on right at runtime) comes to front.
Public Class Home
Dim ucSummary As New ucSummary
Dim ucPermitMain As New ucPermitMain
Dim ucLotoMain As New ucLotoMain
Dim ucHotWorkMain As New ucHotWorkMain
Private Sub Home_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
lblDate.Text = Format(Now, "MMMM dd, yyyy")
lblTime.Text = Format(Now, "h:mm tt")
btnSummary.BackColor = Color.LightGreen
Panel2.Controls.Add(ucSummary)
ucSummary.Dock = DockStyle.Fill
Panel2.Controls.Add(ucPermitMain)
ucPermitMain.Dock = DockStyle.Fill
Panel2.Controls.Add(ucLotoMain)
ucLotoMain.Dock = DockStyle.Fill
Panel2.Controls.Add(ucHotWorkMain)
ucHotWorkMain.Dock = DockStyle.Fill
End Sub
Private Sub btnSummary_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSummary.Click
btnSummary.BackColor = Color.LightGreen
btnPermit.BackColor = Color.LightBlue
btnLoto.BackColor = Color.LightBlue
btnHotWork.BackColor = Color.LightBlue
ucSummary.BringToFront()
End Sub
Private Sub btnPermit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPermit.Click
btnSummary.BackColor = Color.LightBlue
btnPermit.BackColor = Color.LightGreen
btnLoto.BackColor = Color.LightBlue
btnHotWork.BackColor = Color.LightBlue
ucPermitMain.BringToFront()
End Sub
Private Sub btnLoto_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoto.Click
btnSummary.BackColor = Color.LightBlue
btnPermit.BackColor = Color.LightBlue
btnLoto.BackColor = Color.LightGreen
btnHotWork.BackColor = Color.LightBlue
ucLotoMain.BringToFront()
End Sub
Private Sub btnHotWork_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHotWork.Click
btnSummary.BackColor = Color.LightBlue
btnPermit.BackColor = Color.LightBlue
btnLoto.BackColor = Color.LightBlue
btnHotWork.BackColor = Color.LightGreen
ucHotWorkMain.BringToFront()
End Sub
End Class
I have just started & currently working on Permit section which works with ucPermitMain usercontrol.
It has a toolstrip (tsPermit) on top & an empty tabcontrol (tcPermit) below.
Toolstrip has buttons "NewPermit, Issue, Close" (for now..more to come with design)
Each time NewPermit is clicked new tabs open parallely with text boxes on it.
When selected a particular tab & "Issue" is clicked, the data on the selected tab's text boxes to be put into database "PTW.accdb", & tab to be closed.
Public Class ucPermitMain
Dim PTW As New OleDb.OleDbConnection
Dim ucPermit As New ucPermit
Dim txtbox As New TextBox
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
PTW = New OleDb.OleDbConnection
PTW.ConnectionString = "Provider=Microsoft.ACE.Oledb.12.0; Data Source=" & Application.StartupPath & "\PTW.accdb"
End Sub
Public Sub tsbtnNewPermit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbtnNewPermit.Click
tsbtnClose.Visible = True
tsbtnClose.Enabled = True
Dim CTP As New CustomTabPage("New PTW", New Object)
Me.tcPermit.TabPages.Add(CTP)
tcPermit.SelectTab(tcPermit.TabPages.Count - 1)
End Sub
Public Sub tsbtnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbtnClose.Click
tcPermit.TabPages.RemoveAt(tcPermit.SelectedIndex)
'This bottom code is telling it to remove the selected tab and countdown minus (-) 1 (one)
If tcPermit.TabPages.Count > 0 Then
tcPermit.SelectTab(tcPermit.SelectedIndex)
Else
tsbtnClose.Visible = False
tsbtnClose.Enabled = False
End If
End Sub
Public Sub tsbtnIssue_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbtnIssue.Click
Dim cmd As New OleDb.OleDbCommand
Dim CTB As CustomTextBox
If Not PTW.State = ConnectionState.Open Then
'open connection if it is not yet open
PTW.Open()
End If
cmd.Connection = PTW
cmd.CommandText = "INSERT INTO tblPermit(ptwNo)" & _
"VALUES('" & ?????????????? & "')"
cmd.ExecuteNonQuery()
End Sub
End Class
CustomTextBox & CustomTabPage are two seperate classes to create these custom controls.
Imports System.Windows.Forms
Public Class CustomTabPage
Inherits TabPage
Public Sub New(ByVal Name As String, ByVal NewConstruct As Object)
InitTextBox(1)
Me.Text = Name
End Sub
Private Sub InitTextBox(ByVal Num As Integer)
Dim LocX As Integer = 10
Dim LocY As Integer = 10
Dim CTB As New CustomTextBox("")
CTB.Location = New System.Drawing.Point(LocX, LocY)
Me.Controls.Add(CTB)
End Sub
End Class
Imports System.Windows.Forms
Public Class CustomTextBox
Inherits TextBox
Public Sub New(ByVal Name As String)
Me.Text = Name
End Sub
End Class
This is only code I have done upto now & they may be not optimized.
Hope you will spend your time to go through.
The lesson here is to have a Data Layer, this layer has all the methods and logic for saving data to the database. When the new tab is built you have a property that allows it to access the Data Layer. It might even need some encapsulation(UserControl) with having a group of control that the same logic for saving/validating data.
You also should show some code - an effort on your part before asking for help.
I had a similar question for DatagridComboboxColumn but that shown me how to use the .itemsource to bind to an array outside of the datagrid. I am having a problem trying to bind to the collection that the datagrid is bound to at runtime.
I have included a working test program for how I am approaching this.
Class MainWindow
Dim ServerInfoArray As List(Of ServerInfo) = New List(Of ServerInfo)
Private Sub GetInfo(ByVal list As List(Of String))
For Each server As String In list
Dim tempip As ComboBoxItem = New ComboBoxItem
Dim tempip2 As ComboBoxItem = New ComboBoxItem
Dim sinfo As ServerInfo = New ServerInfo
tempip.Content = "192.129.123.23"
tempip2.Content = "23.213.223.21"
sinfo.IPArray.Items.Add(tempip)
sinfo.IPArray.Items.Add(tempip2)
sinfo.ServerName = server
ServerInfoArray.Add(sinfo)
DataGrid1.Items.Refresh()
Next
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
Dim serverlist As List(Of String) = New List(Of String)
serverlist.Add("Test")
serverlist.Add("Random")
serverlist.Add("Local")
GetInfo(serverlist)
End Sub
Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
Dim Col_Serial As DataGridTextColumn = New DataGridTextColumn()
Col_Serial.Binding = New Binding("Servername")
Col_Serial.Header = "Servername"
Col_Serial.Width = 40
Dim Col_IPArray = New DataGridComboBoxColumn()
Col_IPArray.Header = "IP Addresses"
Col_IPArray.IsReadOnly = True
'Col_IPArray.ItemsSource = serverInfoArray ' Don't know how to do this.
Col_IPArray.SelectedValuePath = "IPArray"
Col_IPArray.DisplayMemberPath = "IPArray"
DataGrid1.Columns.Add(Col_Serial)
DataGrid1.Columns.Add(Col_IPArray)
DataGrid1.ItemsSource = ServerInfoArray
End Sub
End Class
Class ServerInfo
Dim _Servername As String
Dim _IPArray As ComboBox
Public Property Servername() As String
Get
Return _Servername
End Get
Set(ByVal value As String)
_Servername = value
End Set
End Property
Public Property IPArray As ComboBox
Get
Return _IPArray
End Get
Set(ByVal value As ComboBox)
_IPArray = value
End Set
End Property
Public Sub New()
_Servername = Nothing
_IPArray = New ComboBox
End Sub
End Class
I can get all Strings and Boolean to bind.
I do not know how I can bind this DataGridComboBoxColumn to the list of attached on the property. I cannot use XAML as I need to do this at runtime.
Dim Col_Serial As DataGridComboColumn = New DataGridComboColumn()
Col_Serial.ItemSource = GetData();
Col_Serial.SelectedValuePath = "ID_value";
Col_Serial.DisplayMemberPath = "displya_col";
Col_Serial.Header = "Disk4"
Col_Serial.Width = 40
Col_Serial.IsEnabled= false;
dg.Columns.Add(Col_serial);
I have a datagrid in my vb.net 4.0 wpf project. I have seen many examples in XAML on how to bind a DataGridComboBoxColumn however I need to do this in code as I have auto-generating columns. I switch the datagridbinding source to multiple data sets.
Inside some of these custom classes are a couple lists. I can get text and checkboxes to auto-generate correctly. When it comes across my array (I have tried many different kinds) I just see a textboxcolumn with the words (Collection) in it.
For instance - One screen I am grabbing system information on WMI calls. One of the calls returns all IP addresses on the server (We can have up to 8 IP addresses) I do not want a column per IP address. I would like to include a list of those into the datagrid so you can drop down and see them.
Any suggestions on if this is possible or if I am doing something wrong?
Thank you
Sample Code
Imports System.Collections.ObjectModel
Class MainWindow
Dim ServerInfoArray As ObservableCollection(Of ServerInfo) = New ObservableCollection(Of ServerInfo)
Private ReadOnly _ipAddresses As ObservableCollection(Of String) = New ObservableCollection(Of String)
Private Sub GetInfo(ByVal list As List(Of String))
For Each server As String In list
Dim tempip As List(Of String) = New List(Of String)
Dim sinfo As ServerInfo = New ServerInfo
tempip.Add("192.129.123.23")
tempip.Add("23.213.223.21")
sinfo.IPArray = tempip
sinfo.Servername = server
ServerInfoArray.Add(sinfo)
Next
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
Dim serverlist As List(Of String) = New List(Of String)
serverlist.Add("Test")
serverlist.Add("Random")
serverlist.Add("Local")
GetInfo(serverlist)
End Sub
Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
Dim Col_Serial As DataGridTextColumn = New DataGridTextColumn()
Col_Serial.Binding = New Binding("Servername")
Col_Serial.Header = "Servername"
Col_Serial.Width = 40
Dim Col_IPArray = New DataGridComboBoxColumn()
Col_IPArray.Header = "IP Addresses"
Col_IPArray.IsReadOnly = True
Col_IPArray.ItemsSource = Me._ipAddresses
Col_IPArray.SelectedItemBinding = New Binding("IPArray")
DataGrid1.Columns.Add(Col_Serial)
DataGrid1.Columns.Add(Col_IPArray)
DataGrid1.ItemsSource = ServerInfoArray
End Sub
End Class
Class ServerInfo
Dim _Servername As String
Dim _IPArray As List(Of String)
Public Property Servername() As String
Get
Return _Servername
End Get
Set(ByVal value As String)
_Servername = value
End Set
End Property
Public Property IPArray As List(Of String)
Get
Return _IPArray
End Get
Set(ByVal value As List(Of String))
_IPArray = value
End Set
End Property
Public Sub New()
_Servername = Nothing
_IPArray = New List(Of String)
End Sub
End Class
Not sure if I am understanding perfectly but if you can live with AutoGenerateColumns = False then you can manipulate the columns, their properties and bindings from code like below. So you could use whatever logic you need to in order setup the columns from code. I tried to show how you can source the combobox column items from a different object than the items in the DataGrid as well.
This is meant to be a simple example so I just did everything in the code-behind but from an MVVM standpoint, it depends on your preferred approach but possibility is that you could accomplish the same logic from a controller class that spins up your view models, etc...
Hope it helps!
XAML...
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<Button x:Name="btnRefreshIPList">Refresh list of IPs</Button>
<DataGrid x:Name="dataGrid1"></DataGrid>
</StackPanel>
</Window>
Code behind...
Imports System.Collections.ObjectModel
Class MainWindow
'The list of IPs for column's ItemSource property
Private ReadOnly _ipAddresses As ObservableCollection(Of String)
'The items for binding to the DataGrid's ItemsSource
Private _items As List(Of MyObjectWithIPAddress)
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
_ipAddresses = New ObservableCollection(Of String)
_items = New List(Of MyObjectWithIPAddress)
End Sub
Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
Me.dataGrid1.AutoGenerateColumns = False
dataGrid1.Columns.Clear()
'Example of text column (Text bound to Name property)
Dim dgTxtCol = New DataGridTextColumn()
dgTxtCol.Header = "Name"
dgTxtCol.Binding = New Binding("Name")
dataGrid1.Columns.Add(dgTxtCol)
'Example of combobox column (SelectedItem bound to IPAddress)
Dim dgCmbCol = New DataGridComboBoxColumn()
dgCmbCol.Header = "IP Address"
dgCmbCol.ItemsSource = Me._ipAddresses
dgCmbCol.SelectedItemBinding = New Binding("IPAddress")
dataGrid1.Columns.Add(dgCmbCol)
'Add items to DataGrid
_items.Add(New MyObjectWithIPAddress("foo1"))
_items.Add(New MyObjectWithIPAddress("foo2"))
Me.dataGrid1.ItemsSource = Me._items
End Sub
''' <summary>
''' To emulate fetching the object that has the IP list
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Private Function GetIpList() As MyObjectWithListOfIPs
Dim inst = New MyObjectWithListOfIPs
inst.IPList = New List(Of String)(New String() {"10.0.0.1", "10.0.0.2", "10.0.0.3"})
Return inst
End Function
''' <summary>
''' Updates the ObservableCollection instance based on business object
''' </summary>
''' <remarks></remarks>
Private Sub RefreshIpAddresses()
_ipAddresses.Clear()
For Each ip As String In GetIpList().IPList
_ipAddresses.Add(ip)
Next
End Sub
Private Sub btnRefreshIPList_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles btnRefreshIPList.Click
RefreshIpAddresses()
End Sub
End Class
''' <summary>
''' Object with response data (e.g., list of IPs)
''' </summary>
''' <remarks></remarks>
Class MyObjectWithListOfIPs
Private _ipList As List(Of String)
Public Property IPList() As List(Of String)
Get
Return _ipList
End Get
Set(ByVal value As List(Of String))
_ipList = value
End Set
End Property
End Class
''' <summary>
''' Disperate object that "has an" address
''' </summary>
''' <remarks></remarks>
Class MyObjectWithIPAddress
Public Sub New(name As String)
Me._name = name
End Sub
Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Private _ipAddress As String
Public Property IPAddress() As String
Get
Return _ipAddress
End Get
Set(ByVal value As String)
_ipAddress = value
End Set
End Property
End Class
I want, that if a cell/row goes to edit mode, then, if the user attempts to select a different row, it should try to commit that row, if the row is not committed sucessfully, it should decline the selection request and the editing row should remain selected and in edit mode.
Do you have experience with a good helper for it? any good workaround?
NOTE: I've been struggling with this issue for a long time and already got some experience, so please post only working examples, not random thoughts.
The code bellow is includes extension from here (code normalized to fit StackOverflow screen witdh, sorry).
Imports System.ComponentModel
Imports System.Windows.Threading
Namespace Components
Public NotInheritable Class DataGridSelectionChangingBehavior
Public Shared Function GetEnableSelectionChanging(
ByVal element As DataGrid) As Boolean
If element Is Nothing Then Throw New ArgumentNullException("element")
Return element.GetValue(EnableSelectionChangingProperty)
End Function
Public Shared Sub SetEnableSelectionChanging(
ByVal element As DataGrid, ByVal value As Boolean)
If element Is Nothing Then Throw New ArgumentNullException("element")
element.SetValue(EnableSelectionChangingProperty, value)
End Sub
Public Shared ReadOnly EnableSelectionChangingProperty As _
DependencyProperty =
DependencyProperty.RegisterAttached("EnableSelectionChanging",
GetType(Boolean),
GetType(DataGridSelectionChangingBehavior),
New FrameworkPropertyMetadata(False,
New PropertyChangedCallback(
AddressOf EnableSelectionChanging_PropertyChanged)))
Public Shared Sub AddSelectionChangingHandler(
ByVal element As DataGrid, handler As SelectionChangingEventHandler)
If element IsNot Nothing Then _
element.AddHandler(
DataGridSelectionChangingBehavior.SelectionChangingEvent, handler)
End Sub
Public Shared Sub RemoveSelectionChangingHandler(
ByVal element As DataGrid, handler As SelectionChangingEventHandler)
If element IsNot Nothing Then _
element.RemoveHandler(
DataGridSelectionChangingBehavior.SelectionChangingEvent, handler)
End Sub
Public Shared ReadOnly SelectionChangingEvent As RoutedEvent =
EventManager.RegisterRoutedEvent("SelectionChanging",
RoutingStrategy.Bubble,
GetType(SelectionChangingEventHandler),
GetType(DataGridSelectionChangingBehavior))
Private Shared Sub EnableSelectionChanging_PropertyChanged(
ByVal sender As Object, ByVal e As DependencyPropertyChangedEventArgs)
Dim dataGrid = DirectCast(sender, DataGrid)
If CBool(e.NewValue) Then
AddHandler dataGrid.PreparingCellForEdit,
AddressOf DataGrid_PreparingCellForEdit
AddHandler dataGrid.SelectionChanged,
AddressOf DataGrid_SelectionChanged
Else
RemoveHandler dataGrid.PreparingCellForEdit,
AddressOf DataGrid_PreparingCellForEdit
RemoveHandler dataGrid.SelectionChanged,
AddressOf DataGrid_SelectionChanged
RecentColumn.Remove(dataGrid)
End If
End Sub
Private Shared Sub DataGrid_SelectionChanged(
ByVal sender As Object, ByVal e As SelectionChangedEventArgs)
If e.RemovedItems.Count = 0 Then Exit Sub
Dim dataGrid = DirectCast(sender, DataGrid)
Dim removed = e.RemovedItems(0)
Dim row = dataGrid.GetContainerFromItem(Of DataGridRow)(removed)
Dim scea As New SelectionChangingEventArgs(row,
DataGridSelectionChangingBehavior.SelectionChangingEvent, dataGrid)
dataGrid.RaiseEvent(scea)
If scea.Cancel Then
RemoveHandler dataGrid.SelectionChanged,
AddressOf DataGrid_SelectionChanged
Dim operation = dataGrid.Dispatcher.BeginInvoke(
Sub()
dataGrid.SelectedItem = removed
Dim column As DataGridColumn = Nothing
If RecentColumn.TryGetValue(dataGrid, column) Then
Dim cellsPanel =
row.GetVisualDescendant(Of DataGridCellsPanel)().
Children.Cast(Of DataGridCell)()
Dim recentCell =
If(cellsPanel.SingleOrDefault(
Function(cell) cell.Column Is column),
cellsPanel.FirstOrDefault)
If recentCell IsNot Nothing Then
recentCell.IsEditing = True
Keyboard.Focus(recentCell)
End If
End If
End Sub,
DispatcherPriority.ContextIdle)
AddHandler operation.Completed,
Sub(s, ea) AddHandler dataGrid.SelectionChanged,
AddressOf DataGrid_SelectionChanged
End If
End Sub
Private Shared m_RecentColumn As Dictionary(Of DataGrid, DataGridColumn)
Public Shared ReadOnly Property RecentColumn() As Dictionary(Of DataGrid,
DataGridColumn)
Get
If m_RecentColumn Is Nothing Then m_RecentColumn =
New Dictionary(Of DataGrid, DataGridColumn)()
Return m_RecentColumn
End Get
End Property
Private Shared Sub DataGrid_PreparingCellForEdit(
ByVal sender As Object, e As DataGridPreparingCellForEditEventArgs)
Dim dataGrid = DirectCast(sender, DataGrid)
RecentColumn(dataGrid) = e.Column
End Sub
End Class
Public Delegate Sub SelectionChangingEventHandler(
ByVal sender As Object, ByVal e As SelectionChangingEventArgs)
Public Class SelectionChangingEventArgs : Inherits RoutedEventArgs
Public Sub New(ByVal row As DataGridRow, routedEvent As RoutedEvent)
MyBase.New(routedEvent)
m_CurrentRow = row
End Sub
Public Sub New(ByVal row As DataGridRow,
ByVal routedEvent As RoutedEvent,
ByVal source As Object)
MyBase.New(routedEvent, source)
m_CurrentRow = row
End Sub
Private m_CurrentRow As DataGridRow
Public ReadOnly Property CurrentRow() As DataGridRow
Get
Return m_CurrentRow
End Get
End Property
Public ReadOnly Property Item() As Object
Get
If CurrentRow IsNot Nothing Then Return CurrentRow.Item
Return Nothing
End Get
End Property
Public Property Cancel As Boolean
End Class
End Namespace
Usage:
<DataGrid Name="dg"
src:DataGridSelectionChangingBehavior.EnableSelectionChanging="True"
src:DataGridSelectionChangingBehavior.SelectionChanging="dg_SelectionChanging">
Code behind (pseudu):
Private Sub dg_SelectionChanging(ByVal sender As Object,
ByVal e As SelectionChangingEventArgs)
If e.CurrentRow.IsEditing Then
Dim item = TryCast(e.CurrentRow.Item, MyEntityType)
If item IsNot Nothing AndAlso item.IsValid Then
Dim dataGrid = DirectCast(sender, DataGrid)
Dim committed = dataGrid.CommitEdit(DataGridEditingUnit.Row, True)
If committed Then Exit Sub
End If
e.Cancel = True
End If
End Sub
Note: visual studio might not show the event in the intellisense and might even generate a design-time error, but it should compile and work perfect.
FYI: code formatted modified to fit SO screen.
How do I obtain the values (not displayed text) of all the selected items in a List Box?
My intention is to use the values (which represent primary and foreign keys in my databases) to assemble a sql query.
Specs: Using WinForm with a .Net Framework v.4
You can also use any object you like in a list box. Small example below, but to test you'll have to create a form with a ListBox and button on it.
Same idea as the dictionary but this will work with more complex objects.
Public Class Form1
Dim tests As New List(Of Test)
Class Test
Private _Key As Integer
Public Property Key() As Integer
Get
Return _Key
End Get
Set(ByVal value As Integer)
_Key = value
End Set
End Property
Private _value As String
Public Property Value() As String
Get
Return _value
End Get
Set(ByVal value As String)
_value = value
End Set
End Property
End Class
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
With tests
.Add(New Test With {.Key = 1, .Value = "Val1"})
.Add(New Test With {.Key = 2, .Value = "Val2"})
.Add(New Test With {.Key = 3, .Value = "Val3"})
End With
ListBox1.SelectionMode = SelectionMode.MultiSimple
ListBox1.DisplayMember = "Value"
For Each t In tests
ListBox1.Items.Add(t)
Next
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For Each t As Test In ListBox1.SelectedItems
Debug.WriteLine(t.Key)
Next
End Sub
End Class