是的你可以; 你应该处理事件。例如,在这种情况下,您处理“TextBox.GotFocus”事件。
void tb_GotFocus(object sender, GotFocusEventArgs e)
{
// here you can get the StackPanel as the parent of the textBox and
// search for the Lable
TextBox tb=(TextBox)sender;
StackPanel sp=tb.Parent as StackPanel;
// and ...
}
如果您想完成此示例,请告诉我。
编辑
这是一个工作示例:
使用此窗口显示结果:
Window win = new Window();
StackPanel stack = new StackPanel { Orientation = Orientation.Vertical };
stack.Children.Add(new CustomControl());
stack.Children.Add(new CustomControl());
stack.Children.Add(new CustomControl());
stack.Children.Add(new CustomControl());
win.Content = stack;
win.ShowDialog();
这是 CustomControl 类:
public class CustomControl : Border
{
Label theLabel = new Label {Content="LableText" };
TextBox theTextbox = new TextBox {MinWidth=100 };
public CustomControl()
{
StackPanel sp = new StackPanel { Orientation=Orientation.Horizontal};
this.Child = sp;
sp.Children.Add(theLabel);
sp.Children.Add(theTextbox);
theTextbox.GotFocus += new RoutedEventHandler(tb_GotFocus);
theTextbox.LostFocus += new RoutedEventHandler(tb_LostFocus);
}
void tb_GotFocus(object sender, RoutedEventArgs e)
{
theLabel.Background = Brushes.Yellow;
}
void tb_LostFocus(object sender, RoutedEventArgs e)
{
theLabel.Background = Brushes.Transparent;
}
}