单击项目时如何更改数据模板?

时间:2012-06-19 20:35:22

标签: c# wpf xaml

ItemsControl DataTemplate看起来像这样:

enter image description here

我想在用户点击项目时实现效果 - 它会垂直展开并显示更多信息。

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

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

2 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分:0)

我不确定我是否正确地关注了这个问题,但它是否就像您正在寻找的DataGrid RowDetails功能?它显示所选项目的详细信息面板:

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