2012-06-19 68 views
1

ItemsControlDataTemplate,看起来像这样:如何在点击项目时更改数据模板?

enter image description here

我想,当用户点击项目达到的效果 - 它垂直展开并显示更多的信息。

我在想的唯一方法是将其更改为ListBox并为选定的常规视图创建2 DataTemplates

但我宁愿注册点击Grid并在我的虚拟机上翻转属性以展开此框。当用户点击Grid MVVM方式时,有没有办法注册?

+0

你希望能够同时扩大多个项目?如果是这样,用户将如何折叠扩展项目? ItemsControl不是选择器,因此它不会注册SelectedItem。你最好使用ListBox。 –

回答

1

您可以使用MouseDown事件的附加行为。
请参见下面的问题:WPF/MVVM - how to handle double-click on TreeViewItems in the ViewModel?

在你的情况下,它看起来像这样

<ItemsControl ItemsSource="{Binding ...}"> 
    <ItemsControl.ItemContainerStyle> 
     <Style TargetType="ContentPresenter"> 
      <Setter Property="commandBehaviors:MouseDown.Command" 
        Value="{Binding YourItemClickCommand}"/> 
      <Setter Property="commandBehaviors:MouseDown.CommandParameter" 
        Value="{Binding}"/> 
     </Style> 
    </ItemsControl.ItemContainerStyle> 
    <!-- ... --> 
</ItemsControl> 

的MouseDown

public class MouseDown 
{ 
    public static DependencyProperty CommandProperty = 
     DependencyProperty.RegisterAttached("Command", 
              typeof(ICommand), 
              typeof(MouseDown), 
              new UIPropertyMetadata(CommandChanged)); 

    public static DependencyProperty CommandParameterProperty = 
     DependencyProperty.RegisterAttached("CommandParameter", 
              typeof(object), 
              typeof(MouseDown), 
              new UIPropertyMetadata(null)); 

    public static void SetCommand(DependencyObject target, ICommand value) 
    { 
     target.SetValue(CommandProperty, value); 
    } 

    public static void SetCommandParameter(DependencyObject target, object value) 
    { 
     target.SetValue(CommandParameterProperty, value); 
    } 
    public static object GetCommandParameter(DependencyObject target) 
    { 
     return target.GetValue(CommandParameterProperty); 
    } 

    private static void CommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs e) 
    { 
     Control control = target as Control; 
     if (control != null) 
     { 
      if ((e.NewValue != null) && (e.OldValue == null)) 
      { 
       control.MouseDown += OnMouseDown; 
      } 
      else if ((e.NewValue == null) && (e.OldValue != null)) 
      { 
       control.MouseDown -= OnMouseDown; 
      } 
     } 
    } 

    private static void OnMouseDown(object sender, RoutedEventArgs e) 
    { 
     Control control = sender as Control; 
     ICommand command = (ICommand)control.GetValue(CommandProperty); 
     object commandParameter = control.GetValue(CommandParameterProperty); 
     command.Execute(commandParameter); 
    } 
} 
相关问题