从 C# 代码隐藏访问 XAML 控件 [英] Access XAML controls from C# code-behind

查看:28
本文介绍了从 C# 代码隐藏访问 XAML 控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 VS 项目中有两个文件:Custom.xamlCustom.cs

I have two files in my VS project: Custom.xaml and Custom.cs

在我的 XAML 文件中,我有以下文本框:

In my XAML file, I have the following text boxes:

<TextBox x:Name="TextBox1" Text="{Binding Value, Mode=TwoWay}" Foreground="Black" Background="Green" SelectionChanged="TextBox1_SelectionChanged" />

<TextBox x:Name="TextBox2" Text="{Binding Value, Mode=TwoWay}" Foreground="Black" Background="Green" SelectionChanged="TextBox2_SelectionChanged" />

在我的 .cs 中,我有以下方法:

In my .cs, I have the following method:

 void TextBox1_SelectionChanged(object sender, RoutedEventArgs e)
 {
     TextBox t = e.Source as TextBox
 }

我可以成功命中上面的事件处理程序.然后,我可以使用 e.Source 获取 TextBox1 及其属性,但我想访问 TextBox2 及其属性.

I can successfully hit the event handler above. Then, I can grab TextBox1 and it's properties by using e.Source, but I would like to access TextBox2 and it's properties.

作为旁注,.cs 文件只是我引用的 C# 类,而不是 xaml.cs.此外,我知道我可以通过 UserControl 实现这一点,但由于本文范围之外的原因,在这种情况下不能这样做.

As a sidenote, the .cs file is just a C# class that I am referencing, not a xaml.cs. Additionally, I understand that I could implement this via a UserControl, but cannot do that in this scenario for reasons that are outside the scope of this post.

请告诉我如何获取/设置 TextBox2 的属性.

Please advise on how I can get/set properties of TextBox2.

谢谢.

关于此的任何其他输入?作为一种解决方法,我添加了一个名为 TextBox2_Loaded 的事件处理程序,然后将 e.Source 设置为一个实例变量.然后,在 TextBox1_SelectionChanged 中,我可以访问实例变量.真的很想直接定位控件(例如 TextBox2.IsEnabled).我一定在某处遗漏了声明或继承.甚至无法使用 FindName 找到控件.

Any other input on this? As a workaround, I've added an event handler called TextBox2_Loaded, and then set e.Source to an instance variable. Then, in TextBox1_SelectionChanged, I can access the instance variable. Would really like to just target the control directly (ex. TextBox2.IsEnabled). I must be missing a declaration or inheritance somewhere. Can't even find the control using FindName.

推荐答案

好吧,我显然在这篇文章中遗漏了一个关键组件...我的 TextBox 控件位于 DataTemplate 控件内.根据我的研究,在 DataTemplate 控件内部时无法访问 TextBox 控件.我真的不认为这很重要,但我猜当这种情况存在时不会创建实例变量.

Alright, so I apparently had left out a critical component in this post... My TextBox controls are inside of DataTemplate controls. From my research, the TextBox controls cannot be accessed when inside of DataTemplate controls. I really didn't think that would matter, but I guess the instance variables are not created when this scenario exists.

如果我对此解释有误,请提供意见.现在,我已经添加了一个 Loaded 事件并将我的 TextBox 控件定义为实例变量,以便我可以在发生其他活动时访问它们并更改属性.

If I've interpreted this incorrectly, please provide input. For now, I've gone ahead and added a Loaded event and defined my TextBox controls as instance variables so that I can access them and change properties when other activities occur.

感谢大家的投入.

这篇关于从 C# 代码隐藏访问 XAML 控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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