WPF MVVM COMMOND 传参

原文:WPF MVVM COMMOND 传参

一、直接绑定(对于有事件的控件可以通过直接绑定的方式)

1、view

  1. <hc:SideMenuItem Header="接谈中" Cursor="Hand" Command="{Binding AddTabItemCommand}" CommandParameter="PDjtList.xaml">
  2. <hc:SideMenuItem.Icon>
  3. <Image Source="/Images/icons/jtz.png" Width="24" Height="24"/>
  4. </hc:SideMenuItem.Icon>
  5. </hc:SideMenuItem>

2、viewmodel

  1. /// <summary>
  2. /// 命令:传递参数
  3. /// </summary>
  4. public RelayCommand<string> AddTabItemCommand =>
  5. new Lazy<RelayCommand<string>>(() =>
  6. new RelayCommand<string>(AddTabItem)).Value;
  7. /// <summary>
  8. /// 添加新页面
  9. /// </summary>
  10. /// <param name="param"></param>
  11. private void AddTabItem(string param)
  12. {
  13. string test = param;
  14. }

二、EventTrigger绑定(对于通过datatemp遍历的控件没有事件可以绑定的情况,如listbox)

WPF MVVM COMMOND 传参

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
  1. <ListBox Name="sideMenu" SelectedIndex="{Binding MenuSelectedIndex}" ItemsSource="{Binding MenuList}" BorderThickness="0" SelectionMode="Single">
  2. <ListBox.ItemTemplate>
  3. <DataTemplate>
  4. <DockPanel Height="40">
  5. <Image Width="20" Height="20" Source="{Binding Icons}"/>
  6. <TextBlock Margin="10,12,0,0" FontSize="14" Text="{Binding Title}"/>
  7. <TextBox x:Name="param" Visibility="Hidden" Text="{Binding Url}"/>
  8. </DockPanel>
  9. </DataTemplate>
  10. </ListBox.ItemTemplate>
  11. <i:Interaction.Triggers>
  12. <i:EventTrigger EventName="SelectionChanged">
  13. <command:EventToCommand Command="{Binding ElementName=sideMenu, Path=DataContext.SelectMenuCommand}" PassEventArgsToCommand="True" />
  14. </i:EventTrigger>
  15. </i:Interaction.Triggers>
  16. </ListBox>
  1. /// <summary>
  2. /// 菜单选择事件
  3. /// </summary>
  4. public RelayCommand<SelectionChangedEventArgs> SelectMenuCommand =>
  5. new Lazy<RelayCommand<SelectionChangedEventArgs>>(() =>
  6. new RelayCommand<SelectionChangedEventArgs>(SelectMenu)).Value;
  7. /// <summary>
  8. /// 选中菜单打开页面
  9. /// </summary>
  10. private void SelectMenu(SelectionChangedEventArgs e)
  11. {
  12. if (e.AddedItems.Count == 0) return;
  13. if (e.AddedItems[0] is MenuInfo item)
  14. {
  15. if (Equals(_selectedMenu, item)) return;
  16. _selectedMenu = item;
  17. DataList.Add(new TabControlModel
  18. {
  19. Header = item.Title,
  20. Url = item.Url
  21. });
  22. TabSelectedIndex = DataList.ToArray().Length - 1;
  23. }
  24. }

三、Image点击事件

  1. <Image x:Name="img_verifycode" Height="40" Margin="0,10,30,0" Source="{Binding VerifyCode}"></Image>
  2. <i:Interaction.Triggers>
  3. <i:EventTrigger EventName="MouseLeftButtonDown">
  4. <command:EventToCommand Command="{Binding ElementName=img_verifycode, Path=DataContext.SwitchVerifyCodeCommand}" />
  5. </i:EventTrigger>
  6. </i:Interaction.Triggers>

 

 

 

 

 

 

 

 

 

 

 

 

WPF MVVM COMMOND 传参

上一篇:【前端开发API】豆瓣开放API


下一篇:WPF MVVM 子页面控制主窗体新增tab页面