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));
        }
    }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM