WPF框架和页面获取事件 [英] WPF Frame and Page Get event

查看:66
本文介绍了WPF框架和页面获取事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is that possible in wpf, in main window will capture the event of the page inside the frame element?

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

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

如果已单击该按钮,则主窗口中的文本块会将文本更新为"Page1 Button click".

If the button has been clicked, the textblock in the main window will update the text to "Page1 Button click".

推荐答案

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

If you use MVVM patter this would be very easy:

定义您的ViewModel类:

Define your ViewModel class:

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 :

Then in your Window set the DataContext:

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

在查看代码中设置绑定:

Set the binding inside the 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>

如您所见,有任何事件委托,但只有处理按钮单击的命令.您可以在此处找到更多信息:命令原始命令

As you can see there is any event delegate, but just a command that handle the click of the button. You can find more informations here: Mvvm Basics; Commands; Prism Command

这篇关于WPF框架和页面获取事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆