简体   繁体   中英

access user control stackpanel from main window WPF

i have a user control which defined like this:

<UserControl x:Class="LearnWPF1.DesignerPanel"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<ScrollViewer VerticalScrollBarVisibility="Auto">
    <StackPanel     
              PreviewMouseDown="panel_PreviewMouseDown"          
              x:Name="panel"
              Orientation="Vertical" 
              Background="White"
              AllowDrop="True"
              DragOver="panel_DragOver"
              Drop="panel_Drop"/>
</ScrollViewer>

now i want my main window to have access on the stackpanel, how can i do that? currently my main window get the user control reference like this:

<local:DesignerPanel x:Name="DesignerPanel"></local:DesignerPanel>

the problem now is the PreviewMouseDown event only works on UserControl's code behind, if i do that on MainWindow, it wont works.

XAML in the MainWindow :

<local:DesignerPanel x:Name="DesignerPanel" 
                     PreviewMouseDown="DesignerPanel_OnPreviewMouseDown"/>

Code-behind in the MainWindow.cs

private void DesignerPanel_OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    // do something
}

您可以像这样从MainWindow访问StackPanel

StackPanel panel = DesignerPanel.panel;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM