且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以访问框架当前页面的DataContext?怎么样?

更新时间:2023-12-01 19:40:10

I我不确定它是否对您有用,因为我仍然不了解您的体系结构中视图模型与模型之间的关系,但请尝试使用以下想法:

I'm not sure that it will work for you, because I still don't understand the relationship between view models and models in your architecure, but try to use this idea:

1)。我的Window1的xaml具有以下内容:

1). My Window1's xaml has following content :

<Grid>       
    <Frame Panel.ZIndex="1"
           x:Name="MainFrame"
           JournalOwnership="OwnsJournal"
           NavigationUIVisibility="Hidden"
           Source="UserControl1.xaml" />
</Grid>

2)UserControl1具有DataContext的定义:

2) UserControl1 has definition of DataContext:

 public UserControl1()
    {
        InitializeComponent();
        DataContext = new MainViewModel();
    }

3)。我提取并修改框架内容的DataContext的代码:

3). The code where I extract and modfy the DataContext of the Content of my Frame:

   Window1 window = new Window1();
        //window.Content = uc;


        var aa = window.Content as Grid;

        foreach (var e in aa.Children)
        {
            if (e is Frame)
            {
                Frame f = e as Frame;
                f.ContentRendered += F_ContentRendered;
            }
        }

//only inside of handler of ContentRendered event you can access to the content of your Frame:
  private void F_ContentRendered(object sender, EventArgs e)
    {
        var frame = sender as Frame;
        UserControl1 uc1 = frame.Content as UserControl1;
        MainViewModel mvm = uc1.DataContext as MainViewModel;

    }

应该可以。