Jonas
Jonas

Reputation: 67

Access Textblock in Controltemplate in App.xaml, in App.xaml.cs

I Have a Control Template similar to this in the App.xaml:

 <ControlTemplate x:Key="Register" >
  <Grid>
   <TextBox Name="REGUSEBOX"/>
   <ButtonName="REGBUTTON" Click="Button_Click" />
  </Grid
 </ControlTemplate>

The Button_Click method was generated in the App.xaml.cs and it works fine, But I can't access the the Textbox.

How can i access the Textbox in the Click method? Thanks

Upvotes: 3

Views: 1203

Answers (3)

ASh
ASh

Reputation: 35680

sender of Click event here is a Button. you can cast it to Button type, take parent (which is Grid), find parent's child element by name and cast it to TextBox

private void Button_Click(object sender, RoutedEventArgs e)
{
    Button button = sender as Button;
    Grid grd = button.Parent as Grid;
    TextBox txt = grd.FindName("REGUSEBOX") as TextBox;
}

note: wpf approach usually doesn't require such manipulations. Binding for TextBox + Command for Button should allow to do all the job in model, not in code behind. if controls have to change their apperance depending on some conditions, Style and Triggers can help

Upvotes: 1

zhangyiying
zhangyiying

Reputation: 424

The first parameter is the Button Object.

Button button = sender as Button;

the button is what you want. But, I suggest use MVVM Pattern in developing of WPF.

If you want know more. Here go

Upvotes: 0

Tim Pohlmann
Tim Pohlmann

Reputation: 4430

This should do the trick:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Button button = sender as Button;
}

Upvotes: 0

Related Questions