WPF 设置Frame中Page的DataContext

WPF窗体MainWindow中有 Frame控件,名为 MainFrame,
MainFrame 通过ViewModel绑定Source属性来设置显示的Page页,
其中的Page页需要与MainWindow 共用一个ViewModel对象做DataContext

MainWindow.xaml

<Border Margin="5" Background="White" CornerRadius="4" Padding="6" Grid.Row="1">
                <Frame Margin="0" x:Name="MainFrame" NavigationUIVisibility="Hidden" LoadCompleted="MainFrame_LoadCompleted" Source="{Binding PageUri,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}" />
</Border>

MainWindow.xaml.cs


        public MainWindow()
        {
            InitializeComponent();
            _viewModel = new ViewModel();
            this.DataContext = _viewModel;
        }
        
        private void MainFrame_LoadCompleted(object sender, NavigationEventArgs e)
        {
            var content = MainFrame.Content as FrameworkElement;//获取当前Frame中的Page
            if (content == null)
            {
                return;
            }
            content.DataContext = this.DataContext;//设置Page的DataContext
        }

ViewModel.cs

private Uri pageUri;
//当前Frame显示的PageUri,即Source属性值,通过设置此属性值来管理Frame的显示
        public Uri PageUri {
            get
            {
                if (pageUri==null)
                {
                    pageUri = new Uri("Pages/Page1.xaml",UriKind.Relative);
                }
                return pageUri;
            }

            set
            {
                pageUri = value;
                OnPropertyChanged(nameof(PageUri));
            }
        }

ViewModelBase.cs

public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
posted @ 2021-05-25 18:12  God Li  阅读(1339)  评论(0编辑  收藏  举报