Search code examples
avaloniaui

Binding property to control


How do I bind SourceObject and TargetObject to the TextBox-Element?

This works, but I want more than one textbox and that does not seem to be possible when they are named the same.

My goal is to have the TextBox change its background color when focused.

<TextBox xmlns="https://github.com/avaloniaui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:i="clr-namespace:Avalonia.Xaml.Interactivity;assembly=Avalonia.Xaml.Interactivity"
             xmlns:ia="clr-namespace:Avalonia.Xaml.Interactions.Core;assembly=Avalonia.Xaml.Interactions"
             x:Class="Test.View.CustomTextBox"

             Name="textBox">

  <i:Interaction.Behaviors>
    <ia:EventTriggerBehavior EventName="GotFocus" SourceObject="{Binding #textBox}">
      <ia:ChangePropertyAction TargetObject="{Binding #textBox}" PropertyName="Background" Value="{StaticResource FocusedBackgroundColor}"/>
    </ia:EventTriggerBehavior>
  </i:Interaction.Behaviors>

</TextBox>

Thanks a lot!


Solution

  • You can use RelativeSource and converter, something like that:

    public class BoolColorBrushConverter : IValueConverter
    {
        public Brush TrueBrush {get;set;}
        public Brush FalseBrush {get;set;}
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
             if(value is bool b && b)
                  return TrueBrush;
             else
                  return FalseBrush;
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotSupportedException();
    }
    

    xaml:

    <MyControl>
        <MyControl.Resources>
           <BoolBrushConverter TrueColor="Red" FalseColor="Blue" x:Key="TextBoxFocusedBackgroundConverter"/>
        </MyControl.Resources>
        <TextBox Background="{Binding IsFocused, RelativeSource={RelativeSource Self}, Converter={StaticResource TextBoxFocusedBackgroundConverter}}}"/>;
    </MyControl>