WPF框架和页面获取事件
在wpf中,是否可能在主窗口中捕获框架元素内的页面事件WPF框架和页面获取事件,wpf,events,Wpf,Events,在wpf中,是否可能在主窗口中捕获框架元素内的页面事件 <Window> <Grid> <TextBlock x:Name="lblEvent"/> <Frame Source="Page1.xaml"/> </Grid> </Window> <Page> <Grid> <Button Content="Click Me"/>
<Window>
<Grid>
<TextBlock x:Name="lblEvent"/>
<Frame Source="Page1.xaml"/>
</Grid>
</Window>
<Page>
<Grid>
<Button Content="Click Me"/>
</Grid>
</Page>
如果已单击按钮,主窗口中的文本块将更新文本为“Page1 button click”。如果使用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>
正如您所看到的,有任何事件委托,但只有一个处理按钮单击的命令。你可以在这里找到更多信息: