问题
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