在wpf中,是否可能在主窗口中捕获frame元素内的页面事件?
<Window>
<Grid>
<TextBlock x:Name="lblEvent"/>
<Frame Source="Page1.xaml"/>
</Grid>
</Window>
<Page>
<Grid>
<Button Content="Click Me"/>
</Grid>
</Page>
如果已单击按钮,则主窗口中的文本块会将文本更新为“ Page1 Button click”。
答案 0 :(得分:0)
如果使用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;
}
}
在查看代码中设置绑定:
<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 Basics; Commands; Prism Command