Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
WPF框架和页面获取事件_Wpf_Events - Fatal编程技术网

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"/>

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

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

正如您所看到的,有任何事件委托,但只有一个处理按钮单击的命令。你可以在这里找到更多信息: