jQuery可以选择Child of Some,Parent或next标签。 C#是否有类似于此行为的内容。例如,我的横向StackPanel
有一个Label
,一个TextBox和一个Button
。
如果当前选择Label
而不使用引用TextBox
名称的if else语句,是否可以定位Label
以更改颜色?有些功能类似StackPanel
中的“此标签”,此TextBox
就在其中。
示例:每当选择一个文本框时,它旁边的标签都会变为黄色背景。
我不知道如何用C#编写这个,所以我会尝试用常规文本来解释。
if (this) textbox is selected
get the label next to it
change the label background to a color
else
remove the color if it is not selected
Method()将根据当前选定的TextBox
。
这样的函数可以使用相同的代码,但一旦焦点更改为其他Labels
,就可以定位不同的TextBox
。这可能吗?
答案 0 :(得分:1)
是的,你可以;你应该处理事件。例如,在这种情况下,您处理'TextBox.GotFocus` event。
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;
}
}