如何通过GotFocus事件触发器修改WPF TextBox的Text属性绑定
纯XAML实现TextBox焦点切换Text绑定的方案
方案一:使用Style Trigger(推荐,无需额外程序集)
通过TextBox的Style触发器,根据IsFocused属性动态切换Text的绑定表达式,代码如下:
<TextBox> <TextBox.Style> <Style TargetType="TextBox"> <!-- 无焦点时的默认绑定 --> <Setter Property="Text" Value="{Binding ShortValue, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" /> <!-- 焦点状态切换触发器 --> <Style.Triggers> <Trigger Property="IsFocused" Value="True"> <!-- 获得焦点时切换绑定到Value --> <Setter Property="Text" Value="{Binding Value, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" /> </Trigger> </Style.Triggers> </Style> </TextBox.Style> </TextBox>
说明:
- 默认状态下,TextBox绑定
ShortValue - 当
IsFocused属性变为True时,触发器会覆盖默认的Text绑定,切换到Value - 失去焦点后,触发器自动失效,Text绑定恢复为默认的
ShortValue
方案二:使用Interaction.Triggers(需额外程序集)
如果要基于你最初写的i:Interaction.Triggers实现,需要先引用System.Windows.Interactivity和Microsoft.Expression.Interactions程序集,再通过ChangePropertyAction切换绑定:
<!-- 先添加命名空间 --> xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" <!-- TextBox代码 --> <TextBox Text="{Binding ShortValue, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay, UpdateSourceTrigger=LostFocus}"> <i:Interaction.Triggers> <!-- 获得焦点时切换绑定 --> <i:EventTrigger EventName="GotFocus"> <ei:ChangePropertyAction PropertyName="Text"> <ei:ChangePropertyAction.Value> <Binding Path="Value" RelativeSource="{RelativeSource TemplatedParent}" Mode="TwoWay" UpdateSourceTrigger="LostFocus" /> </ei:ChangePropertyAction.Value> </ei:ChangePropertyAction> </i:EventTrigger> <!-- 失去焦点时切回原绑定 --> <i:EventTrigger EventName="LostFocus"> <ei:ChangePropertyAction PropertyName="Text"> <ei:ChangePropertyAction.Value> <Binding Path="ShortValue" RelativeSource="{RelativeSource TemplatedParent}" Mode="TwoWay" UpdateSourceTrigger="LostFocus" /> </ei:ChangePropertyAction.Value> </ei:ChangePropertyAction> </i:EventTrigger> </i:Interaction.Triggers> </TextBox>
说明:
- 两个
EventTrigger分别监听GotFocus和LostFocus事件 - 通过
ChangePropertyAction直接修改TextBox的Text属性绑定,实现切换逻辑
内容的提问来源于stack exchange,提问作者Tommer
相关产品推荐
相关产品推荐

