Richard
Richard

Reputation: 155

Invoking a WPF view (UserControl) method from the main window (Window)

I have a button on a view (UserControl) that invokes a method in the code-behind file. I would like to get rid of the button and instead, invoke the method from a menu item. Not sure how to do this. Here is some simple code illustrating this situation:

MainWindow.xaml (MainView is embedded):

<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");
    }
  }
}

Upvotes: 2

Views: 2496

Answers (1)

lightlike
lightlike

Reputation: 162

You could just give a name to the 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>

and call the Method like this:

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

Upvotes: 2

Related Questions