Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set event handler method inside xaml tag

Tags:

wpf

xaml

Is there any opportunity to set event handler inside xaml without using c#, powershell etc.? For example I would like to set text of another control after click. Below is a "pseudo code" of what I want to do:

<Button Content="Set value = text1" OnClick="txt1.Text = text1" />
<Button Content="Set value = text2" OnClick="txt1.Text = text2" />
<Textbox Name="txt1" />
like image 340
nosbor Avatar asked May 22 '26 16:05

nosbor


1 Answers

You can write inline c# in xaml. Altho that is just something you should rather be avoiding at all costs. If you absolutely have to, you could do something like:

<StackPanel>
  <Button Content="Set value = text1" Click="InlineHandler" />
  <Button Content="Set value = text2" Click="InlineHandler"  />
  <TextBox Name="txt1" />
  <x:Code>
    <![CDATA[            
          private void InlineHandler(object sender, RoutedEventArgs e) {
            var btn = sender as Button;
            if (btn == null)
              return;
            txt1.Text = btn.Content.ToString() == "Set value = text1" ? "text1" : "text2";
          }
      ]]>
  </x:Code>
</StackPanel>

MSDN Link - Code-Behind and XAML in WPF

In simple terms, you're just defining the event handler inline in xaml than in the code-behind.

Again do not resort to this approach unless you're proving a point.

like image 125
Viv Avatar answered May 25 '26 07:05

Viv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!