【问题标题】:WPF Frame and Page Get eventWPF 框架和页面获取事件
【发布时间】:2018-08-02 06:31:32
【问题描述】:

在 wpf 中是否可能,在主窗口中会捕获框架元素内的页面事件?

 <Window>
   <Grid>
     <TextBlock x:Name="lblEvent"/>
     <Frame Source="Page1.xaml"/>
   </Grid>
</Window>

<Page>
   <Grid>
        <Button Content="Click Me"/>
   </Grid>
</Page>

如果按钮已被点击,主窗口中的文本块会将文本更新为“Page1 Button click”。

【问题讨论】:

    标签: wpf events


    【解决方案1】:

    如果您使用 MVVM 模式,这将非常容易:

    定义你的 ViewModel 类:

    class MyViewModel:INotifyPropertyChanged
    {
       private string _LabelText;
       public string LabelText
        {
            get
            {
                return this._LabelText;
            }
    
            set
            {
                if (value != this._LabelText)
                {
                    this._LabelText = value;
                    NotifyPropertyChanged();
                }
            }
        }
    
        private DelegateCommand _ClickCommand;
        public readonly DelegateCommand ClickCommand
        {
            get
            {
                if(_ClickCommand == null)
                {
                    _ClickCommand = new DelegateCommand(()=>LabelText="LabelText Changed!");            
                }   
                return _ClickCommand;
            }
        }
    
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    

    然后在你的窗口中设置DataContext:

    public class MainWindow
    {
        private MyViewModel vm;
        public MainWindow()
        {
            InitializeComponent();
            this.vm = new MyViewModel()
            DataContext = vm;
        }
    }
    

    在View Code里面设置绑定:

    <Window>
       <Grid>
         <TextBlock x:Name="lblEvent" Text="{Binding LabelText}"/>
         <Frame Source="Page1.xaml"/>
       </Grid>
    </Window>
    
    <Page>
       <Grid>
            <Button Content="Click Me" Command="{Binding ClickCommand}"/>
       </Grid>
    </Page>
    

    正如您所见,有任何事件委托,但只是一个处理按钮单击的命令。您可以在这里找到更多信息:Mvvm BasicsCommands; Prism Command

    【讨论】:

      猜你喜欢
      • 2012-01-05
      • 1970-01-01
      • 2010-10-20
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多