VB.NET эквивалент C # кода - PullRequest
       15

VB.NET эквивалент C # кода

0 голосов
/ 19 июля 2010

У меня есть фрагмент кода в C #, но я не могу конвертировать в VB.NET.Я пробовал онлайн-конвертеры, но VS2008 всегда выдает ошибки компиляции.Любая помощь очень ценится.

foreach (Binding knownBinding in allKnownBindings)
{
    string errorMessage = ((IDataErrorInfo)this.DataContext)[knownBinding.Path.Path];
    if (errorMessage != null && errorMessage.Length > 0)
    {
        isValid = false;

        // Display the error on any elements bound to the property
        FindBindingsRecursively(
        this.Parent,
        delegate(FrameworkElement element, Binding binding, DependencyProperty dp)
        {
            if (knownBinding.Path.Path == binding.Path.Path)
            {

                BindingExpression expression = element.GetBindingExpression(dp);
                ValidationError error = new ValidationError(
                        new ExceptionValidationRule(), expression, errorMessage, null);
                System.Windows.Controls.Validation.MarkInvalid(expression, error);

                if (_firstInvalidElement == null)
                {
                    _firstInvalidElement = element;
                }
                return;
            }
        });
    }
}

и эквивалент VB.Net, который я получил:

For Each knownBinding As Binding In allKnownBindings
    Dim errorMessage As String = DirectCast(Me.DataContext, IDataErrorInfo)(knownBinding.Path.Path)
    If errorMessage IsNot Nothing AndAlso errorMessage.Length > 0 Then
        isValid = False

        ''# Display the error on any elements bound to the property
        FindBindingsRecursively(Me.Parent, Function(element As FrameworkElement, binding As Binding, dp As DependencyProperty) Do
            If knownBinding.Path.Path = Binding.Path.Path Then

                Dim expression As BindingExpression = element.GetBindingExpression(dp)
                Dim [error] As New ValidationError(New ExceptionValidationRule(), expression, errorMessage, Nothing)
                System.Windows.Controls.Validation.MarkInvalid(expression, [error])

                If _firstInvalidElement Is Nothing Then
                    _firstInvalidElement = element
                End If

                Return
            End If
        End Function)
    End If
Next

Ответы [ 3 ]

3 голосов
/ 19 июля 2010

Попробуйте бесплатный сервис , но убедитесь, что вы предоставили ему действительный код C #.


UPDATE:

Полагаю, причина, по которой компилятор VB.NET задыхается, заключается в том, что анонимная функция передана FindBindingsRecursively. Попробуйте преобразовать (деанонимизировать) это в отдельный метод:

Sub FindASuitableName(element As FrameworkElement, binding As Binding, dp As DependencyProperty)
    If knownBinding.Path.Path = binding.Path.Path Then
        Dim expression As BindingExpression = element.GetBindingExpression(dp)
        Dim [error] As New ValidationError(New ExceptionValidationRule(), expression, errorMessage, Nothing)
        System.Windows.Controls.Validation.MarkInvalid(expression, [error])

        If _firstInvalidElement Is Nothing Then
            _firstInvalidElement = element
        End If
    End If
End Sub

А затем используйте его напрямую:

FindBindingsRecursively(Me.Parent, FindASuitableName)
0 голосов
/ 19 июля 2010

Существуют переменные, которые необходимо сохранить в классе, чтобы метод делегата имел к ним доступ.

Public Class BindingWork
...
Private binding As Binding
Private path As String
Private error_msg As String

Public Sub Start()

    Dim errinfo As IDataErrorInfo = CType(Me.DataContext, IDataErrorInfo)
    For Each knownBinding As Binding In allKnownBindings
        error_msg = errinfo(knownBinding.Path.Path)
        If Not String.IsNullOrEmpty(error_msg) Then
            isValid = False
            Me.path = knownBinding.Path.Path
            FindBindingsRecusively(Me.Parent, AddressOf WorkWithBindings)
        End If
    Next

End Sub

Sub WorkWithBindings(ByVal element As FrameworkElement, ByVal binding As Binding, ByVal dp As DependencyProperty)
    If path = binding.Path.Path Then
        Dim expression As BindingExpression = element.GetBindingExpression(dp)
        Dim [error] As New ValidationError(New ExceptionValidationRule(), expression, error_msg, Nothing)
        System.Windows.Controls.Validation.MarkInvalid(expression, [error])
        If _firstInvalidElement Is Nothing Then
            _firstInvalidElement = element
        End If
    End If
End Sub
...
End Class

Обратите внимание, что ваш обработчик делегата использует path, error_msg, _firstInvalidElement и «переплет».

0 голосов
/ 19 июля 2010

Попробуйте использовать Telerik C # / VB конвертер.

http://converter.telerik.com/

Он может конвертировать полные файлы или фрагменты.

...