WPF 使用System.Windows.Interactivity互動事件
1.引用System.Windows.Interactivity,在右鍵,新增引用->擴充套件裡找到此dll新增
XAML中使用該dll
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
Triggers 示例1
<!-- TextBox控制元件的獲得焦點、失去焦點事件 -->
<TextBox Text="Test">
<i:Interaction.Triggers>
<i:EventTrigger EventName="LostFocus">
CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1, AncestorType={x:Type TextBox}}}"/>
<i:EventTrigger EventName="GotFocus">
<i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource AncestorType=Window},Path=DataContext.OnTextGotFocus}"
CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1, AncestorType={x:Type TextBox}}}"/>
</i:Interaction.Triggers>
</TextBox>
由於VS中不支援System.Windows.Interactivity的智慧提示,經常要查閱這個EventTrigger還能觸發哪些方法,所有EventName的列表如下:
MSDN中Grid Eventshttps://msdn.microsoft.com/en-us/library/system.windows.controls.grid_events(v=vs.110).aspx
Behavior 示例2
作用:當文字框中輸入的網址改變時,觸發的事件
public class TextBoxBindingUpdateOnEnterBehaviour : Behavior<TextBox>
{
protected override void OnAttached()
{
AssociatedObject.KeyDown += OnTextBoxKeyDown;
}
protected override void OnDetaching()
{
AssociatedObject.KeyDown -= OnTextBoxKeyDown;
}
private void OnTextBoxKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
var txtBox = sender as TextBox;
txtBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();
}
}
}
xaml
xmlns:behaviours=“clr-namespace:CefSharp.MinimalExample.Wpf.Behaviours”
<TextBox x:Name="txtBoxAddress" Text="{Binding Address, ElementName=Browser, FallbackValue=www.google.com}" Grid.Column="2" FontSize="12" BorderBrush="Gray" BorderThickness="1">
<i:Interaction.Behaviors>
<behaviours:TextBoxBindingUpdateOnEnterBehaviour />
</i:Interaction.Behaviors>
</TextBox>