2012-06-19 4 views
1

У меня есть ItemsControl с DataTemplate который выглядит следующим образом:Как изменить шаблон данных при нажатии элемента?

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); 
    } 
} 
0

Я не уверен, что я следую за вопрос, но правильно это что-то вроде функции DataGrid RowDetails, которую вы ищете? Он показывает панель детализации выбранных элементов:

http://wpftutorial.net/DataGrid.html#rowDetails

Смежные вопросы