【问题标题】:RelativeSource FindAncestor without static resource in MVVM?MVVM中没有静态资源的RelativeSource FindAncestor?
【发布时间】:2011-03-19 23:25:20
【问题描述】:

我是 WPF 和 MVVM 模式的新手,所以我的绑定有一些问题。

在客户的详细信息视图中,我想在组合框中列出一些状态。

在我的 ViewModel 中,客户处于根级别,状态列表也是如此。

当使用静态资源时,我可以使用:

ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}}, Path=DataContext.PartGruppAll}"

在我的 ComboBox 上,但是当我从后面的代码中设置 DataContext 时,它不起作用,我做错了什么,在我看来应该没有区别。

最好的问候, 彼得·拉尔森

【问题讨论】:

  • 或许也可以给我们viewmodel代码。它可能会有所帮助

标签: wpf mvvm combobox binding


【解决方案1】:

在您的绑定中,尝试将 AncestorType 设置为您的视图类。类似的东西

ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type vw:MyView}}, Path=DataContext.PartGruppAll}"

其中 vw 是您保持查看的名称空间,而 MyView 是您的视图类本身的名称。

在我的应用程序中,我已经这样声明了 vw

xmlns:vw="clr-namespace:MyApp.View"

(你可能不需要那个位,但我包括在内以防万一=)

【讨论】:

    【解决方案2】:

    我会尽量给你一些更多的细节,viewmodel 非常大,所以我会尽量缩短它。

    我在 App.xaml 后面的代码中实例化视图模型

            protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
    
            PartWindow pw = new PartWindow();
    
    
            var PartViewModel = new ViewModel.PartWindowViewModel();
            pw.DataContext = PartViewModel;
    
            pw.Show();
        }
    

    然后在我的页面中,我将数据绑定到堆栈面板:

    <StackPanel DataContext="{Binding Path=PartViewModel}">
    

    然后我通过绑定到客户属性 SelectedPart 在网格中显示客户。

       <Grid DataContext="{Binding SelectedPart}" Margin="5" Grid.Column="0">
    

    我的 viewModel 看起来像这样:

    视图模型类

    • 选定部分

    名称和其他属性

    • 状态列表

    名称和其他属性

    我认为没什么复杂的...网格与选定的客户相关联,这就是问题所在。

    【讨论】:

      【解决方案3】:

      哦还有一件事......

      如果 StackPanel 与组合框位于同一可视树上,则无需在绑定中找到它

      ItemsSource="{Binding PartGruppAll}" 
      

      应该可以在可视化树中搜索 DataCoxtext。

      【讨论】:

        【解决方案4】:

        这不是因为你可能有拼写错误

        Path=DataContext.PartGruppAll
        

        应该是

        Path=DataContext.PartGroupAll
        

        【讨论】:

        • 不,抱歉,该名称中有瑞典语的一部分,正确的名称实际上是 PartGruppAll。 :)
        • 好吧,别担心……只是预感
        猜你喜欢
        • 1970-01-01
        • 2011-01-25
        • 2010-11-22
        • 1970-01-01
        • 2011-01-18
        • 2013-03-07
        • 1970-01-01
        • 2020-07-21
        • 2018-09-01
        相关资源
        最近更新 更多