2013-02-06 25 views
0

У меня странная проблема в моем проекте. Есть страницы, сделанные из usercontrol и панели меню (также usercontrol).wpf Usercontrol in usercontrol no response

Вот мой UserControl, который содержит несколько кнопок

public partial class UpperBar : UserControl 
{  
    public UpperBar() 
    { 
     InitializeComponent(); 
    } 

    public event EventHandler EventbtClicked; 
    private void btConnect_Click(object sender, System.Windows.RoutedEventArgs e) 
    { 
     EventbtClicked(this, e); 
    }  
} 

Я добавил это в моей странице следующим образом:

<local:UpperBar VerticalAlignment="Top" Grid.Row="0" Height="78" Grid.ColumnSpan="3" Margin="0,2,0,0"/> 

И в моей странице пытались вызвать событие:

public PageStatus() 
{ 
    InitializeComponent(); 
    Plc.ExecuteRefresh += new EventHandler(RefreshLeds); 


    UpperBar.EventbtCliced += new EventHandler(UpperBatButtonClick); 
} 

protected void UpperBarButtonClick(object sender, EventArgs e) 
{ 
    //do something 
} 

Но я не могу получить доступ к своему мероприятию, используя это UpperBar.EventbtCliced, почему?

+0

что Plc? Я не вижу, что вы называете свой элемент управления в xaml –

+0

Я предполагаю, что 'EventbtCliced' является опечаткой, а вы имеете в виду:' EventbtClicked'? – CodingGorilla

ответ

2

Вам нужно получить доступ к экземпляру вашего класса UpperBar в PageStatus, а не самому классу UpperBar!

Самый простой способ для вас здесь:

  • Имя вашей UpperBar в вашем XAML, например:

<local:UpperBar x:Name="_myBar" x:FieldModifier="private"/>

  • Затем используйте этот экземпляр в вашем PageStatus.xaml. cs:

    public partial class MainWindow : Window { 
    public MainWindow() 
    { 
        InitializeComponent(); 
    
        _myBar.EventbtClicked += new EventHandler(UpperBarButtonClick); 
    } 
    
    protected void UpperBarButtonClick(object sender, EventArgs e) 
    { 
        //do something 
    } 
    

    }

Теперь, если вы работаете серьезно в WPF, вы действительно должны узнать о Databinding и MVVM, ловя событие таким образом, это не самый лучший способ сделать это на всех.

0

Вы должны использовать пользовательскую команду (RoutedUICommand), а не пузырьковое событие из пользовательского элемента управления.

вот некоторые шаги, чтобы следовать, в отличие от вашего подхода:

1: создать класс myCustomCommand.

 namespace WpfApplication1 

     { 

     public class myCustomCommand. 
      { 

       private static RoutedUICommand _luanchcommand;//mvvm 

       static myCustomCommand.() 
        { 
       System.Windows.MessageBox.Show("from contructor"); // static consructor is             called when static memeber is first accessed(non intanciated object) 
     InputGestureCollection gesturecollection = new InputGestureCollection(); 
     gesturecollection.Add(new KeyGesture(Key.L,ModifierKeys.Control));//ctrl+L 
     _luanchcommand =new RoutedUICommand("Launch","Launch",typeof(myCustomCommand.),gesturecollection); 

    } 
    public static RoutedUICommand Launch 
    { 
     get 
     { 
      return _luanchcommand; 
     } 
    } 

} 

    } 

В XAML из UserControl:

    <UserControl x:Class="WpfApplication1.UserControl1" 

     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:CustomCommands="clr-namespace:WpfApplication1" 

     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     mc:Ignorable="d" 
     d:DesignHeight="300" d:DesignWidth="300"> 

       <UserControl.CommandBindings> 
       <CommandBinding Command="CustomCommands:myCustomCommand.Launch" Executed="CommandBinding_Executed"> 

    </CommandBinding> 
</UserControl.CommandBindings> 
<Grid > 
    <TextBox Name="mytxt" Height="30" Width="60" Margin="50,50,50,50" ></TextBox> 
    <Button Name="b" Height="30" Width="60" Margin="109,152,109,78" Command="CustomCommands:ZenabUICommand.Launch"></Button> 

</Grid> 

Теперь в коде управления пользователя

Ручка command_executed

private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) 
    { 
     mytxt.Text = "invoked on custom command"; 
    } 
} 

}