在App.xaml.cs中的App.xaml中访问Controltemplate中的Textblock

时间:2016-02-18 13:32:58

标签: c# wpf xaml

我在 App.xaml

中有一个类似于此的控制模板
 <ControlTemplate x:Key="Register" >
  <Grid>
   <TextBox Name="REGUSEBOX"/>
   <ButtonName="REGBUTTON" Click="Button_Click" />
  </Grid
 </ControlTemplate>

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

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

3 个答案:

答案 0 :(得分:1)

这里sender事件的{p> ClickButton。您可以将其转换为Button类型,取父级(Grid),按名称查找父级子元素并将其强制转换为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方法通常不需要这样的操作。绑定TextBox + Command for Button应该允许在模型中完成所有工作,而不是在后面的代码中。如果控件必须根据某些条件更改其外观,则样式和触发器可以提供帮助

答案 1 :(得分:0)

这应该可以解决问题:

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

答案 2 :(得分:0)

第一个参数是Button对象。

Button button = sender as Button;

按钮就是你想要的。但是,我建议在开发WPF时使用MVVM模式。

如果你想了解更多。 Here go

相关问题