lundi 11 mai 2015

Event Triggers not working in Code Behind

I want create WPF controls at Runtime dynamically. In the below code, I have added StackPanel at XAML and crated Button/TextBlock/Triggers at code behind. I want to see TextBlock under button at MouseEnter action and want to hide TextBlock at MouseLeave action. This is not working as expected. If add Button/Textblock code at XAML (commented now) Instead of creating them at Code behind(un commented now) then it is working fine. Please let me know how to fix this? Not able understand why this not working If I create the button at runtime instead of XAML code. Thanks

XAML

<Grid>
   <StackPanel Name="stackPanel5" >
      <!--
      <Button Name="Button1" Cursor="Hand" Content="Press Me"/>
      <Border x:Name="TooltipBrd" BorderBrush="Black" BorderThickness="10,0,10,10" HorizontalAlignment="Center"  VerticalAlignment="Center"  Visibility="Collapsed">
         <TextBlock Margin="0,10,0,0" x:Name="myTextBlock" Text="Coded Test" />
      </Border>
      -->
   </StackPanel>
</Grid>

code

public void LoadData()
{
   //VisualState vs = new VisualState();
   //vs.SetValue(FrameworkElement.NameProperty, YourStateName);

   Button Button1 = new Button() { Cursor = Cursors.Hand, Content = "Press Me!" };
   stackPanel5.Children.Add(Button1);

   Border TooltipBrd = new Border()
   {
       BorderBrush = Brushes.Black,
       BorderThickness = new Thickness(10, 10, 10, 10),
       HorizontalAlignment = HorizontalAlignment.Center,
       VerticalAlignment = VerticalAlignment.Center,
       Visibility = Visibility.Collapsed
   };

   TextBlock txtB1 = new TextBlock() { Text = "Lakshman", Margin = new Thickness(0, 100, 0, 0) };
   TooltipBrd.Child = txtB1;

   stackPanel5.Children.Add(TooltipBrd);

   System.Windows.Interactivity.EventTrigger trigger1 = new System.Windows.Interactivity.EventTrigger();
   trigger1.EventName = "MouseEnter";

   ChangePropertyAction action1 = new ChangePropertyAction();
   action1.TargetName = "TooltipBrd";
   action1.PropertyName = "Visibility";
   action1.Value = Visibility.Visible;

   trigger1.Actions.Add(action1);
   trigger1.Attach(Button1);

   System.Windows.Interactivity.EventTrigger trigger2 = new System.Windows.Interactivity.EventTrigger();
   trigger2.EventName = "MouseLeave";

   ChangePropertyAction action2 = new ChangePropertyAction();
   action2.TargetName = "TooltipBrd";
   action2.PropertyName = "Visibility";
   action2.Value = Visibility.Collapsed;

   trigger2.Actions.Add(action2);
   trigger2.Attach(Button1);
}

Aucun commentaire:

Enregistrer un commentaire