-1

jQueryは、何かの子、親、または次のタグを選択できます。C#にはこの動作に似たものがありますか?たとえば、、TextBox、およびを含む水平線StackPanelがあります。LabelButton

の名前を参照するifelseステートメントを使用せずに、が現在選択されているLabel場合、色を変更するようにターゲットにできますか?これが入っているこの中の「このラベル」のようないくつかの機能。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 に答える