88473166 2020-01-08
一、直接绑定(对于有事件的控件可以通过直接绑定的方式)
1、view
<hc:SideMenuItem Header="接谈中" Cursor="Hand" Command="{Binding AddTabItemCommand}" CommandParameter="PDjtList.xaml"> <hc:SideMenuItem.Icon> <Image Source="/Images/icons/jtz.png" Width="24" Height="24"/> </hc:SideMenuItem.Icon> </hc:SideMenuItem>
2、viewmodel
/// <summary> /// 命令:传递参数 /// </summary> public RelayCommand<string> AddTabItemCommand => new Lazy<RelayCommand<string>>(() => new RelayCommand<string>(AddTabItem)).Value; /// <summary> /// 添加新页面 /// </summary> /// <param name="param"></param> private void AddTabItem(string param) { string test = param; }
二、EventTrigger绑定(对于通过datatemp遍历的控件没有事件可以绑定的情况,如listbox)
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
<ListBox Name="sideMenu" SelectedIndex="{Binding MenuSelectedIndex}" ItemsSource="{Binding MenuList}" BorderThickness="0" SelectionMode="Single"> <ListBox.ItemTemplate> <DataTemplate> <DockPanel Height="40"> <Image Width="20" Height="20" Source="{Binding Icons}"/> <TextBlock Margin="10,12,0,0" FontSize="14" Text="{Binding Title}"/> <TextBox x:Name="param" Visibility="Hidden" Text="{Binding Url}"/> </DockPanel> </DataTemplate> </ListBox.ItemTemplate> <i:Interaction.Triggers> <i:EventTrigger EventName="SelectionChanged"> <command:EventToCommand Command="{Binding ElementName=sideMenu, Path=DataContext.SelectMenuCommand}" PassEventArgsToCommand="True" /> </i:EventTrigger> </i:Interaction.Triggers> </ListBox>
/// <summary> /// 菜单选择事件 /// </summary> public RelayCommand<SelectionChangedEventArgs> SelectMenuCommand => new Lazy<RelayCommand<SelectionChangedEventArgs>>(() => new RelayCommand<SelectionChangedEventArgs>(SelectMenu)).Value; /// <summary> /// 选中菜单打开页面 /// </summary> private void SelectMenu(SelectionChangedEventArgs e) { if (e.AddedItems.Count == 0) return; if (e.AddedItems[0] is MenuInfo item) { if (Equals(_selectedMenu, item)) return; _selectedMenu = item; DataList.Add(new TabControlModel { Header = item.Title, Url = item.Url }); TabSelectedIndex = DataList.ToArray().Length - 1; } }
三、Image点击事件
<Image x:Name="img_verifycode" Height="40" Margin="0,10,30,0" Source="{Binding VerifyCode}"></Image> <i:Interaction.Triggers> <i:EventTrigger EventName="MouseLeftButtonDown"> <command:EventToCommand Command="{Binding ElementName=img_verifycode, Path=DataContext.SwitchVerifyCodeCommand}" /> </i:EventTrigger> </i:Interaction.Triggers>