前言,我们在WPF开发中应用MVVM开发模式时,一般用来绑定Button 的Command命令,但是有很多控件MS没有给出Command命令,我们需要添加一个DLL来增加绑定时的属性。
下面来们来看一看。
本次测试有:TextBlock,Labe,TextBox三个 控件。
测试界面如下:
前台代码:
<Window x:Class="NoCommandBingding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style x:Key="Test_TextBox" TargetType="{x:Type TextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Border x:Name="border" Width="Auto" Height="Auto" BorderThickness="1" BorderBrush="#FF7F9DB9">
<Grid x:Name="grid" Background="#FFFFFF">
<ScrollViewer x:Name="PART_ContentHost" VerticalAlignment="Center" HorizontalAlignment="Left"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Background="LightBlue" Text="我是一个Textbook 点击我" TextAlignment="Center" Margin="10" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonUp">
<i:InvokeCommandAction Command="{Binding TextBlockCommand}" CommandParameter="{Binding ElementName=lb}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBlock>
<Label Grid.Row="1" Background="LightYellow" Content=" 我是一个lable 点击我" Margin="10">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonUp">
<i:InvokeCommandAction Command="{Binding LabelCommand}" CommandParameter="{Binding ElementName=lb}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Label>
<TextBox Grid.Row="2" Background="PaleVioletRed" Text="我是一个Textbox 点击我" TextAlignment="Center" Margin="10" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="GotFocus">
<i:InvokeCommandAction Command="{Binding TextBoxCommand}" CommandParameter="{Binding ElementName=lb}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
</Grid>
</Window>
加入一个程序集:
然后在前台文件引用:
有必要说明一下:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
后面的像一个网络地 址的东西并不是去引用了一个网上的程序集,微软只是作为一个命名空间来存放程序集的引用,如此而已。
测试效果:
1.
2.
3.
最后奉上Demo