在 App.xaml 中的 Controltemplate 中访问 Textblock,在 App.xaml.cs 中 [英] Access Textblock in Controltemplate in App.xaml, in App.xaml.cs

查看:26
本文介绍了在 App.xaml 中的 Controltemplate 中访问 Textblock,在 App.xaml.cs 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 App.xaml 中有一个与此类似的控制模板:

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>

Button_Click 方法是在 App.xaml.cs 中生成的,它工作正常,但我无法访问文本框.

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

如何在 Click 方法中访问文本框?谢谢

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

推荐答案

senderClick 事件这里是一个 Button.您可以将其转换为 Button 类型,获取父元素(即 Grid),按名称查找父元素的子元素并将其转换为 TextBox

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;
}

注意:wpf 方法通常不需要这样的操作.绑定文本框 + 按钮命令应该允许在模型中完成所有工作,而不是在代码后面.如果控件必须根据某些条件改变其外观,样式和触发器可以提供帮助

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

这篇关于在 App.xaml 中的 Controltemplate 中访问 Textblock,在 App.xaml.cs 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆