简体   繁体   中英

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

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

This should do the trick:

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

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

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