-1

jQuery 可以选择某物的子项、父项或下一个标记。C# 是否有类似这种行为的东西。例如,我有一个水平仪StackPanel,它有一个Label、一个 TextBox 和一个Button.

如果当前选择了而不使用引用名称的 if else 语句,我可以将目标Label更改为颜色吗?this 所在的 this中的某些功能,例如“此标签” 。TextBoxLabelStackPanelTextBox

示例:无论何时选择一个文本框,它旁边的标签都会变为黄色背景。

在此处输入图像描述

我不确定如何用 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. 这可能吗?

4

1 回答 1

1

是的你可以; 你应该处理事件。例如,在这种情况下,您处理“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;
    }
}
于 2012-12-25T16:55:18.967 回答