Is there a way to prevent a user selecting another row when DataGrid is in edit mode? - wpf

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.

Related

Clear Session cookies in WPF WebBrowser control

I am trying to clear session cookies in a WPF WebBrowser. This method
Public Const INTERNET_OPTION_END_BROWSER_SESSION As Integer = 42
<DllImport("wininet.dll", SetLastError:=True)>
Public Function InternetSetOption(ByVal hInternet As IntPtr, ByVal dwOption As Integer, ByVal lpBuffer As IntPtr, ByVal lpdwBufferLength As Integer) As Boolean
End Function
described here How to clear System.Windows.Forms.WebBrowser session data? works for our WinForms applications, but not for WPF.
Any ideas?
Thanks
Turns out the answer is to ensure that the WebBrowser object is created each time the page is loaded.
As the WebBrowser object is not considered to be a control I created a ScrollViewer at initialisation then added the WebBrowser to the ScrollViewer on the loaded event.
It now works perfectly
for Faber75
Imports System.ComponentModel
Class Website_Login_Page
Private LoginBrowser As WebBrowser
Private Sub Website_Login_Page_Initialized(sender As Object, e As System.EventArgs) Handles Me.Initialized
Try
Website_Login_Grid.Background = New SolidColorBrush(Colors.White)
For i As Integer = 0 To 1
Dim vRow As New RowDefinition
If i = 0 Then
vRow.Height = New GridLength(35, GridUnitType.Star)
Else
vRow.Height = New GridLength(35)
End If
Website_Login_Grid.RowDefinitions.Add(vRow)
Next
Dim SV As New ScrollViewer
With SV
.VerticalScrollBarVisibility = ScrollBarVisibility.Auto
.Name = "Website_Login_SV"
End With
RegisterControl(Website_Login_Grid, SV)
'Cookies are not removed if the WebBrowser object is not created each time the page is loaded!
' LoginBrowser = New WebBrowser
Grid.SetRow(SV, 0)
Website_Login_Grid.Children.Add(SV)
Dim DP As DockPanel = PageStatusBarDP(Website_Login_Grid)
Grid.SetRow(DP, 1)
Website_Login_Grid.Children.Add(DP)
Catch ex As Exception
EmailError(ex)
End Try
End Sub
Private Sub Website_Login_Page_Loaded(sender As Object, e As System.Windows.RoutedEventArgs) Handles Me.Loaded
Try
If LoginBrowser Is Nothing Then
LoginBrowser = New WebBrowser
End If
Dim SV As ScrollViewer = Website_Login_Grid.FindName("Website_Login_SV")
SV.Content = LoginBrowser
AddHandler LoginBrowser.Navigating, AddressOf WebBrowser_Loading
AddHandler LoginBrowser.LoadCompleted, AddressOf WebBrowser_Loaded
AddHandler LoginBrowser.Navigated, AddressOf WebBrowser_Navigated
If InternetSetOption(IntPtr.Zero, INTERNET_OPTION_END_BROWSER_SESSION, IntPtr.Zero, 0) = False Then
MessageBox.Show("Returned False")
End If
With LoginBrowser
.Navigate(New Uri("https://website.com"))
End With
Catch ex As Exception
EmailError(ex)
End Try
End Sub
Private Sub Website_Login_Page_Unloaded(sender As Object, e As System.Windows.RoutedEventArgs) Handles Me.Unloaded
Try
If Not LoginBrowser Is Nothing Then
RemoveHandler LoginBrowser.Navigating, AddressOf WebBrowser_Loading
RemoveHandler LoginBrowser.LoadCompleted, AddressOf WebBrowser_Loaded
RemoveHandler LoginBrowser.Navigated, AddressOf WebBrowser_Navigated
LoginBrowser = Nothing
End If
GC.GetTotalMemory(True)
Catch ex As Exception
EmailError(ex)
End Try
End Sub
Private Sub WebBrowser_Loading(ByVal sender As Object, ByVal e As NavigatingCancelEventArgs)
PageStatusBarLoading(Website_Login_Grid)
PageStatusBarRightChangeText(Website_Login_Grid, "Loading... Please wait...")
End Sub
Private Sub WebBrowser_Loaded(ByVal sender As Object, ByVal e As NavigationEventArgs)
Dim vDoc As Object = LoginBrowser.Document
Dim vTitle As String = vDoc.Title
PageStatusBarLoaded(Website_Login_Grid, vTitle)
PageStatusBarRightChangeText(Website_Login_Grid, "Loaded")
End Sub
Private Sub WebBrowser_Navigated(ByVal sender As Object, ByVal e As NavigationEventArgs)
Dim vDoc As Object = LoginBrowser.Document
Dim vTitle As String = vDoc.Title
PageStatusBarLoaded(Website_Login_Grid, vTitle)
PageStatusBarRightChangeText(Website_Login_Grid, "Loaded")
End Sub
End Class

WPF Datagrid DataGridComboBoxColumn Autogenerate at runtime

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

Binding TextBox to a value that is updated from a different Thread

I tried to increment a value as long as I press a button. The incremented value is connected via binding to a TextBox. The problem occures when I update the underlaying integer. I get an exception that another Thread owns it.
<Button Name="Up"
Content="Up"
PreviewMouseLeftButtonDown="Up_PreviewMouseLeftButtonDown"
PreviewMouseLeftButtonUp="Up_PreviewMouseLeftButtonUp">
</Button>
<TextBox Text="{Binding NumericField}">
During Initialisation:
Timer = New Timers.Timer
Timer.Interval = 100
AddHandler Timer.Elapsed, AddressOf Timer_Elapsed
Code behind:
Private _numericField As Integer
Public Property NumericField As Integer
Get
Return _numericField
End Get
Set(ByVal value As Integer)
_numericField = value
RaiseEvent PropertyChanged(Me, New ComponentModel.PropertyChangedEventArgs("NumericField"))
End Set
End Property
Private Sub Timer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
NumericField += 1
End Sub
Private Sub Up_PreviewMouseLeftButtonDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
Timer.Start()
End Sub
Private Sub Up_PreviewMouseLeftButtonUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
Timer.Stop()
End Sub
This looks a bit too complicated. Can't you use a RepeatButton?
Simple solution:
<RepeatButton Click="RepeatButton_Click" Content="Up" />
Code behind:
Private Sub RepeatButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
NumericField += 1
End Sub
Using commands
Try to avoid unnecessary code in your code behind file. Here's a sketch using Commands
XAML:
<RepeatButton Command="{Binding IncrementField}" Content="Up"></RepeatButton>
Helping class. Re-usable for all commands inside your project:
Public Class ActionCommand
Implements ICommand
Private ReadOnly _executeHandler As Action(Of Object)
Private ReadOnly _canExecuteHandler As Func(Of Object, Boolean)
Public Sub New(ByVal execute As Action(Of Object),
ByVal canExecute As Func(Of Object, Boolean))
If execute Is Nothing Then
Throw New ArgumentNullException("Execute cannot be null")
End If
_executeHandler = execute
_canExecuteHandler = canExecute
End Sub
Public Custom Event CanExecuteChanged As EventHandler Implements ICommand.CanExecuteChanged
AddHandler(ByVal value As EventHandler)
AddHandler CommandManager.RequerySuggested, value
End AddHandler
RemoveHandler(ByVal value As EventHandler)
RemoveHandler CommandManager.RequerySuggested, value
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs)
CommandManager.InvalidateRequerySuggested()
End RaiseEvent
End Event
Public Sub Execute(ByVal parameter As Object) Implements ICommand.Execute
_executeHandler(parameter)
End Sub
Public Function CanExecute(ByVal parameter As Object) As Boolean Implements ICommand.CanExecute
If (_canExecuteHandler Is Nothing) Then
Return True
End If
Return _canExecuteHandler(parameter)
End Function
End Class
And in your model:
_incrementField = New ActionCommand(AddressOf IncrementExecuted, AddressOf IncrementCanExecute)
...
Private Function IncrementCanExecute(ByVal parameter As Object) As Boolean
Return True
End Function
Private Sub IncrementExecuted(ByVal parameter As Object)
NumericField += 1
End Sub
Private _incrementField As ActionCommand
Public ReadOnly Property IncrementField As ActionCommand
Get
Return _incrementField
End Get
End Property

VB.NET WPF NullReference Exception

I have a TreeView with a parent node and two children node. Each of the nodes contain a checkbox stored in a TreeViewItem. I want the two children node checkboxes to be set to IsChecked=true when the user checks the parent node and I want the two children node checkboxes to be IsChecked=false when the user unchecks the parent node.
I have a for loop in which the child node checkboxes are stored in a list. The parent node checkbox check/uncheck event should iterate through the child node checkbox list but I am having a problem aceess the list. For some reason the list equals "nothing" in the parent node check/uncheck event. Can anyone explain how I should be accessing that list?
Here's My Code:
Public Class Question
Dim childCheckbox As CheckBox
Dim childCheckboxes() As CheckBox
Public Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
Dim parentCheckbox = New CheckBox
Dim parentNode = New TreeViewItem
parentCheckbox.Uid = "All Sites"
AddHandler parentCheckbox.Checked, AddressOf chkbox_AllChecked
AddHandler parentCheckbox.Unchecked, AddressOf chkbox_AllUnchecked
parentCheckbox.Content = "All Sites"
parentNode.Header = parentCheckbox
For Each osite In sites
Dim childNode = New TreeViewItem
Dim childCheckbox = New CheckBox
AddHandler childCheckbox.Checked, AddressOf chkbox_Checked
AddHandler childCheckbox.Unchecked, AddressOf chkbox_Unchecked
childCheckbox.Uid = osite.SiteName.ToString
childCheckbox.Content = osite.SiteName.ToString
childNode.Header = childCheckbox
parentNode.Items.Add(childNode)
'Add all childCheckbox to an array for use by parentChildbox methods to check/uncheck all
childCheckboxes(i) = childCheckbox
i += 1
Next
TreeView1.Items.Add(parentNode)
End Sub
Private Sub chkbox_AllChecked(ByVal sender As Object, ByVal e As RoutedEventArgs)
Dim chk = DirectCast(sender, CheckBox)
'MessageBox.Show(chk.Uid.ToString)
'This part doesn't work.
For Each child In childCheckboxes
child.IsChecked = True
Next
End Sub
Private Sub chkbox_Checked(ByVal sender As Object, ByVal e As RoutedEventArgs)
Dim chk = DirectCast(sender, CheckBox)
'MessageBox.Show("Check!")
MessageBox.Show(chk.Uid.ToString)
End Sub
Private Sub chkbox_Unchecked(ByVal sender As Object, ByVal e As RoutedEventArgs)
Dim chk = DirectCast(sender, CheckBox)
'MessageBox.Show("Uncheck!")
MessageBox.Show(chk.Uid.ToString)
End Sub
End Class
Thanks for the help!
Could you try to change the line:
Dim childCheckboxes() As CheckBox
To:
Dim childCheckboxes as new list(of CheckBox)

Raising event in custom control

I'm writing a custom textblock control thats populate hyperlinks and raises event when clicked to hyperlink.
I wrote this code but I got stucked.
My code is :
Imports System.Text.RegularExpressions
Public Class CustomTextBlock
Inherits TextBlock
Public Event Klik As EventHandler(Of EventArgs)
Public ReadOnly InlineCollectionProperty As DependencyProperty = DependencyProperty.Register("InlineCollection", GetType(String), GetType(CustomTextBlock), New PropertyMetadata(New PropertyChangedCallback(AddressOf CustomTextBlock.InlineChanged)))
Private Shared Sub InlineChanged(ByVal sender As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
DirectCast(sender, CustomTextBlock).Inlines.Clear()
Dim kelimeler = Split(e.NewValue, " ")
For i = 0 To kelimeler.Length - 1
If Regex.Match(kelimeler(i), "(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,#?^=%&:/~\+#]*[\w\-\#?^=%&/~\+#])?").Success Then
Dim x = New Hyperlink(New Run(kelimeler(i)))
x.AddHandler(Hyperlink.ClickEvent, New RoutedEventHandler(AddressOf t_Click))
x.ToolTip = kelimeler(i)
x.Tag = kelimeler(i)
DirectCast(sender, CustomTextBlock).Inlines.Add(x)
If Not i = kelimeler.Length Then DirectCast(sender, CustomTextBlock).Inlines.Add(" ")
Else
DirectCast(sender, CustomTextBlock).Inlines.Add(kelimeler(i))
If Not i = kelimeler.Length Then DirectCast(sender, CustomTextBlock).Inlines.Add(" ")
End If
''//Console.WriteLine(kelime(i).ToString.StartsWith("#"))
Next
kelimeler = Nothing
End Sub
Public Property InlineCollection As String
Get
Return DirectCast(GetValue(InlineCollectionProperty), String)
End Get
Set(ByVal value As String)
SetValue(InlineCollectionProperty, value)
End Set
End Property
Private Shared Sub t_Click(ByVal sender As Hyperlink, ByVal e As System.Windows.RoutedEventArgs)
e.Handled = True
RaiseEvent Klik(sender, EventArgs.Empty)
End Sub
End Class
This code gives error at RaiseEvent Klik(sender, EventArgs.Empty)
Error is : Cannot refer to an instance member of a class from within a shared method or shared member initializer without an expliticit instance of the class.
Thanks for your answers,
Alper
The problem is clearly stated in the exception message. The t_Click method is Shared (which means common to all instances of the class), so it cannot raise an Event that is specific to an instance of the class. You should only raise the event from a method that is not shared.
Do something like this -
Imports System
Imports System.Text.RegularExpressions
Public Class CustomTextBlock
Inherits TextBlock
Public Event Klik As EventHandler(Of System.EventArgs)
Public ReadOnly InlineCollectionProperty As DependencyProperty = DependencyProperty.Register("InlineCollection", GetType(String), GetType(CustomTextBlock), New PropertyMetadata(New PropertyChangedCallback(AddressOf CustomTextBlock.InlineChanged)))
Private Shared Sub InlineChanged(ByVal sender As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
Dim d As CustomTextBlock = DirectCast(sender, CustomTextBlock)
d.Inlines.Clear()
d.OnInlineChanged(CType(e.NewValue, String))
End Sub
Private Sub OnInlineChanged(ByVal Value As String)
Dim kelimeler = Split(Value, " ")
For i As Integer = 0 To kelimeler.Length - 1
If Regex.Match(kelimeler(i), "(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,#?^=%&:/~\+#]*[\w\-\#?^=%&/~\+#])?").Success Then
Dim x = New Hyperlink(New Run(kelimeler(i)))
x.AddHandler(Hyperlink.ClickEvent, New RoutedEventHandler(AddressOf t_Click))
x.ToolTip = kelimeler(i)
x.Tag = kelimeler(i)
Me.Inlines.Add(x)
If Not i = kelimeler.Length Then Me.Inlines.Add(" ")
Else
Me.Inlines.Add(kelimeler(i))
If Not i = kelimeler.Length Then Me.Inlines.Add(" ")
End If
''//Console.WriteLine(kelime(i).ToString.StartsWith("#"))
Next
kelimeler = Nothing
End Sub
Public Property InlineCollection As String
Get
Return DirectCast(GetValue(InlineCollectionProperty), String)
End Get
Set(ByVal value As String)
SetValue(InlineCollectionProperty, value)
End Set
End Property
Private Sub t_Click(ByVal sender As Hyperlink, ByVal e As System.Windows.RoutedEventArgs)
e.Handled = True
RaiseEvent Klik(sender, System.EventArgs.Empty)
End Sub
End Class

Resources