【问题标题】:Binding property to control绑定属性到控件
【发布时间】:2018-08-10 21:40:25
【问题描述】:

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

非常感谢!

【问题讨论】:

    标签: avaloniaui


    【解决方案1】:

    你可以使用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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-11
      • 2010-12-11
      • 2019-12-17
      • 1970-01-01
      • 2012-08-29
      • 1970-01-01
      • 2012-05-02
      相关资源
      最近更新 更多