在wpf中,是否可以访问框架当前页面的DataContext?如果是,怎么样?
如果否,我应该使用什么作为框架的替代,以便我可以访问其DataContext?
如果不清楚,请告诉我。
更新:澄清
DataContext
中有Frame
。我想访问string
中显示的当前页面的ViewModel
。我们只想说我要显示当前页面ViewModel
的名为 title 的<Window x:Class="Libertalia.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
.
.
.
DataContext="{Binding Main, Source={StaticResource Locator}}"
>
<ScrollViewer VerticalScrollBarVisibility="Auto">
<Grid>
<Frame Panel.ZIndex="1" x:Name="MainFrame" JournalOwnership="OwnsJournal" NavigationUIVisibility="Hidden" Source="View/BlankPage.xaml" />
</Grid>
</ScrollViewer>
</Window>
属性。 (假设每个页面'<Page x:Class="Libertalia.View.LoginView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:behaviors="clr-namespace:Libertalia.Behavior"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
.
.
.
DataContext="{Binding Page1, Source={StaticResource Locator}}"
<DockPanel Margin="200" >
</DockPanel>
</Page>
都有标题属性)
更新:这是我的MainWindow.xaml
MainWindow.xaml
页面代码(只是其中一个,只是一个示例):
MainViewModel.cs
更新:模型,视图和ViewModel关系
MainWindow.xaml's
(查看)绑定到DataContext
(ViewModel)。简而言之,MainViewModel.cs
MainWindow.xaml
为Frame
Frame
(查看)有Page
Frame
有Page
(查看)。 DataContext
有多个页面,一次显示一个。DataContext
有自己的ViewModel(DataContext
)我想做什么:
ng.probe($0)
访问当前页面(框架)enableProdMode()
。答案 0 :(得分:0)
我不确定它是否适合您,因为我仍然不了解您的架构中视图模型和模型之间的关系,但尝试使用这个想法:
1)。我的Window1的xaml有以下内容:
<Grid>
<Frame Panel.ZIndex="1"
x:Name="MainFrame"
JournalOwnership="OwnsJournal"
NavigationUIVisibility="Hidden"
Source="UserControl1.xaml" />
</Grid>
2)UserControl1定义了DataContext:
public UserControl1()
{
InitializeComponent();
DataContext = new MainViewModel();
}
3)。我提取并修改我的框架内容的DataContext的代码:
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;
}
它应该有用。