Reputation: 2528
Being new to wpf and MVVM it didn't take too long for me to stumble across the little issue of dialog result (or rather the lack of it). Fortunately the number of questions on the subject in SO at least leaves me with the sense that I'm not alone.
Having looked at a myriad of answers the one that seems most akin to the principle of MVVM (at least to my new and relatively non proficient eye) was that given by Joe White here.
So far so good until it came to the little matter of translating it to VB.
What I ended up with was this;
Imports System.windows
Public NotInheritable Class DialogCloser
Private Sub New()
End Sub
Public Shared ReadOnly DialogResultProperty As DependencyProperty = DependencyProperty.RegisterAttached("DialogResult", GetType(System.Nullable(Of Boolean)), GetType(DialogCloser), New PropertyMetadata(DialogResultChanged))
Private Shared Sub DialogResultChanged(d As DependencyObject, e As DependencyPropertyChangedEventArgs)
Dim window = TryCast(d, Window)
If window IsNot Nothing Then
window.DialogResult = TryCast(e.NewValue, System.Nullable(Of Boolean))
End If
End Sub
Public Shared Sub SetDialogResult(target As Window, value As System.Nullable(Of Boolean))
target.SetValue(DialogResultProperty, value)
End Sub
End Class
This gives me two specific errors
When I look again at the original code that Joe posted there appears to be no parameter passed for 'd' and the trycast is much the same as it has been converted to. So why is this throwing errors when converted to VB?
Thanks for any light you can shed on the matter and any suggestions you might have to rectify it.
Upvotes: 0
Views: 175
Reputation: 2137
Here is something that will work:
Public Shared ReadOnly DialogResultProperty As DependencyProperty = DependencyProperty.RegisterAttached(
"DialogResult",
GetType(System.Nullable(Of Boolean)),
GetType(DialogCloser),
New PropertyMetadata(New PropertyChangedCallback(AddressOf DialogResultChanged)))
Private Shared Sub DialogResultChanged(d As DependencyObject, e As DependencyPropertyChangedEventArgs)
Dim window = TryCast(d, Window)
If window IsNot Nothing Then
window.DialogResult = DirectCast(e.NewValue, Nullable(Of Boolean))
End If
End Sub
The problems in your code are (as I understand, I'm not a VB expert):
There is no implicit conversion in VB from what is called in C# "method group" to delegate, so you have to use the AddressOf operator
"as" in C# does not directly translate to TryCast in VB because "as" explicitly supports nullable types. In this case, DirectCast is a safe bet, as you are in charge of the parameters being passed.
Upvotes: 1