将属性绑定到控件

时间:2018-08-10 08:07:48

标签: avaloniaui

如何将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>

非常感谢!

1 个答案:

答案 0 :(得分: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();
}

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>