WPF Frame and Page Get event

你离开我真会死。 提交于 2021-02-11 14:31:29

问题


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>

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


回答1:


If you use MVVM patter this would be very easy:

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

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



来源:https://stackoverflow.com/questions/51646900/wpf-frame-and-page-get-event

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!