从主窗口(Window)调用WPF视图(UserControl)方法

时间:2017-07-19 04:52:23

标签: wpf

我在视图上有一个按钮(UserControl),它调用代码隐藏文件中的方法。我想摆脱按钮,而是从菜单项调用该方法。不知道该怎么做。以下是一些说明这种情况的简单代码:

MainWindow.xaml(嵌入了MainView):

<Window x:Class="Example.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:View="clr-namespace:Example.View"
    Title="MainWindow" Height="600" Width="800"  Background="Green">
<Grid>
    <StackPanel>
        <Menu>
            <MenuItem Header="File" Click="MenuItem_Click">
            </MenuItem>
        </Menu>
        <View:MainView/>
    </StackPanel>
</Grid>

MainWindow.xaml.cs

using System.Windows;

namespace Example
{
  public partial class MainWindow : Window
  {
    private void MenuItem_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("MainWindow");

        // how can I invoke MainView methods like DoWork from here?
    }
  }
}

MainView.xaml

<UserControl x:Class="Example.View.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignHeight="500" d:DesignWidth="600">

<Grid Background="Yellow">
    <Button HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10" Content="Show" Click="Button_Click"/>
</Grid>

</UserControl>

MainView.xaml.cs

using System.Windows.Controls;

namespace Example.View
{
  public partial class MainView : UserControl
  {
    public MainView()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        DoWork();
    }

    public void DoWork()
    {
        MessageBox.Show("MainView");
    }
  }
}

1 个答案:

答案 0 :(得分:2)

您可以为MainView命名,

<Window x:Class="Example.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:View="clr-namespace:Example.View"
    Title="MainWindow" Height="600" Width="800"  Background="Green">
    <Grid>
        <StackPanel>
            <Menu>
                <MenuItem Header="File" Click="MenuItem_Click"/>
            </Menu>
            <View:MainView x:Name="mainView"/>
        </StackPanel>
    </Grid>
</Window>

并像这样调用方法:

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    mainView.DoWork();
}