Problem: Accessing a custom DP on a bound template
This is a small example of what we are trying to do.
I can get the content of each “VerticalButton” in the collection and display it just fine, but we need to be able to get at the “AllowedRoles” dependency property in the template because the end goal is to bind the visibility of the VerticalButton to this property (After creating an IValueConverter). We just can’t seem to wrap our heads around how to get to the AllowedRoles property from the listbox’s ItemTemplate.
The Page.xaml and Class code file can be found below:
Imports System.Windows.Controls.Primitives
Imports System.Collections.ObjectModel
Public Class VerticalButton
Inherits ButtonBase
Public Property AllowedRoles() As String
Get
Return GetValue(AllowedRolesProperty)
End Get
Set(ByVal value As String)
SetValue(AllowedRolesProperty, value)
End Set
End Property
Public Shared ReadOnly AllowedRolesProperty As DependencyProperty = DependencyProperty.Register(“AllowedRoles”, GetType(String), GetType(VerticalButton), New PropertyMetadata(New PropertyChangedCallback(AddressOf OnAllowedRolesChanged)))
Public Shared Sub OnAllowedRolesChanged(ByVal d As DependencyObject, ByVal args As DependencyPropertyChangedEventArgs)
Dim sender As VerticalButton = CType(d, VerticalButton)
sender.AllowedRoles = CStr(args.NewValue)
End Sub
End Class
Public Class VerticalButtonCollection
Inherits ObservableCollection(Of VerticalButton)
End Class
Solution: Accessing a custom DP on a bound template
Ended up getting this working by doing the following. One of the tricks is that you can’t use a converter on a template binding so you bind the DataContext of the object using a template binding and then use a regular binding to access that.
Public Class VerticalButton
Inherits Button
Implements INotifyPropertyChanged
Public Property AllowedRoles() As String
Get
Return CStr(GetValue(AllowedRolesProperty))
End Get Set(ByVal value As String)
SetValue(AllowedRolesProperty, value)
End Set End Property
Public Shared ReadOnly
AllowedRolesProperty As DependencyProperty = DependencyProperty.Register(“AllowedRoles”, GetType(String), GetType(VerticalButton), New PropertyMetadata(New PropertyChangedCallback(AddressOf OnAllowedRolesChanged)))
Public Shared Sub OnAllowedRolesChanged(ByVal d As DependencyObject, ByVal args As DependencyPropertyChangedEventArgs)
Dim sender As VerticalButton = CType(d, VerticalButton)
sender.AllowedRoles = CStr(args.NewValue)
End Sub
Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChangedEnd
ClassPublic Class VerticalButtonCollection
Inherits ObservableCollection(Of VerticalButton)
End Class