• 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));
            }
        }
    
  • 相关阅读:
    Linux2_软件源apt 仓库 包 的概念
    I2C(smbus pmbus)和SPI分析
    Linux1_发型版本(Debian RHEL)与软件包管理器(RPM dpkg)的概念
    ubuntu系统下如何切换输入法
    【NYOJ】[169]素数
    【杭电】[2020]绝对值排序
    【杭电】[2020]绝对值排序
    【NYOJ】[199]无线网络覆盖
    【NYOJ】[243]字母统计
    【NYOJ】[198]数数
  • 原文地址:https://www.cnblogs.com/GodLi/p/14809959.html
Copyright © 2020-2023  润新知