开发者

XAML Named element not found by FindName

开发者 https://www.devze.com 2023-03-13 22:27 出处:网络
I am havi开发者_如何学运维ng problems finding an named object declared in XAML in my codebehind file.

I am havi开发者_如何学运维ng problems finding an named object declared in XAML in my codebehind file.

I want to initalize a ViewModel from inside my View. However I also need a reference to the ViewModel in my code behind file (basically for navigation support, handling events, etc. that I cannot do easily from my ViewModel)

<navigation:Page.DataContext>
    <vm:JobsViewModel x:Name="ViewModel" />
</navigation:Page.DataContext>

However I get a null reference exception when I'm trying to access the ViewModel in my code behind:

    Protected Overrides Sub OnNavigatedTo(ByVal e As System.Windows.Navigation.NavigationEventArgs)
        MyBase.OnNavigatedTo(e)
        ViewModel.Initalize() '<-- Exception here
    End Sub

Some more research shows that the FindName call for "ViewModel" in InitalizeComponent returns null. I tried reading up on XAML namescopes etc. but as far as I see, this should be a simple case and just work, no?

Any pointers as to why this fails would be greatly appreciated. Thanks!


That's because your JobsViewModel is not part of the visual tree, so FindName doesn't find it. You can retrieve it through the DataContext property instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消