0

如何将 SourceObject 和 TargetObject 绑定到 TextBox-Element?

这可行,但我想要多个文本框,而且当它们命名相同时,这似乎是不可能的。

我的目标是让 TextBox 在聚焦时更改其背景颜色。

<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>

非常感谢!

4

1 回答 1

0

您可以使用 RelativeSource 和转换器,例如:

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();
}

xml:

<MyControl>
    <MyControl.Resources>
       <BoolBrushConverter TrueColor="Red" FalseColor="Blue" x:Key="TextBoxFocusedBackgroundConverter"/>
    </MyControl.Resources>
    <TextBox Background="{Binding IsFocused, RelativeSource={RelativeSource Self}, Converter={StaticResource TextBoxFocusedBackgroundConverter}}}"/>;
</MyControl>
于 2018-08-10T13:40:25.107 回答