MVVM DataGrid SelectedItem绑定未更新

时间:2012-07-16 13:03:29

标签: binding mvvm .net-4.0 wpfdatagrid selecteditem

我是.Net和C#的新手,对绑定有点困惑。我有应用程序实现MVVM并显示DataGrid。我想要实现的是当用户按下某个键组合时,当前所选单元格的内容被复制到下面行中的单元格。 我已经尝试将DataGrid的SelectedItem绑定到ViewModel属性,但它永远不会更新。 CommandParameter也没有工作,项目计数始终为0。 因此,我无法提取用户选择的单元格,也无法读取所选单元格的内容。 有没有人有如何解决这个问题或实现这个功能的建议? 提前致谢。 码: XAML:

<DataGrid Grid.Row="1" 
          Grid.Column="0" 
          Grid.ColumnSpan="9" 
          AutoGenerateColumns="False" 
          Height="Auto" 
          HorizontalAlignment="Left" 
          Name="dataGrid" 
          VerticalAlignment="Top" 
          Width="{Binding ElementName=grid4,Path=Width}"
          ScrollViewer.CanContentScroll="False" 
          FrozenColumnCount="1" 
          SelectionUnit="Cell" 
          SelectionMode="Extended" 
          CanUserSortColumns = "False" 
          CanUserReorderColumns="False" 
          CanUserResizeRows="False" 
          RowHeight="25" 
          RowBackground="LightGray" 
          AlternatingRowBackground="White"
          ScrollViewer.VerticalScrollBarVisibility="Visible" 
          ScrollViewer.HorizontalScrollBarVisibility="Visible"
          ItemsSource="{Binding Layers, Mode=TwoWay}"  
          SelectedItem="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.Selection, Mode=TwoWay}">
    <DataGrid.InputBindings>
        <KeyBinding Gesture="Shift" 
                    Command="{Binding ItemHandler}" 
                    CommandParameter="{Binding ElementName=dataGrid, Path=SelectedItems}">
        </KeyBinding>
    </DataGrid.InputBindings>
</DataGrid>

视图模型:

private float _selection = 0.0f;
    public float Selection
    {
        get
        {
            return _selection;
        }
        set
        {
            if (_selection != value)
            {
                _selection = value;
                NotifyPropertyChanged("Selection");
            }
        }
    }

...

        public DelegateCommand<IList> SelectionChangedCommand = new DelegateCommand<IList>(
        items =>
        {
            if (items == null)
            {
                NumberOfItemsSelected = 0; 
                return;
            }
            NumberOfItemsSelected = items.Count;
        });
    public ICommand ItemHandler
    {
        get
        {
            return SelectionChangedCommand;
        }
    }

2 个答案:

答案 0 :(得分:7)

编辑: SelectionUnit =单元格不能与SelectedItem一起使用

这是正常的mvvm方式:

第一个你想要在每一行显示的对象类型

 public class MyObject {}

第二个包含集合和所选项目的视图模型

 public class MyViewmodel
 {
    public ObservableCollection<MyObject> MyItems {get;set;}
    public MyObject MySelectedItem {get;set;}

 }

xaml datagrid

 <DataGrid ItemsSource="{Binding MyItems}" SelectedItem="{Binding MySelectedItem, Mode=TwoWay}"/>

这就是你所拥有的。如果您现在想创建一个“复制”行的命令,您可以创建一个新对象MyObject并从MySelectedItem复制值,然后将新的MyObject添加到您的集合中。

但也许我的问题不对。

答案 1 :(得分:0)

我认为您可以添加依赖项属性。这是财产答案:

public class UIElementMouseRightButtonDownCommandBehavior : CommandBehaviorBase<UIElement>
{
    public UIElementMouseRightButtonDownCommandBehavior(UIElement obj)
        : base(obj)
    {
        if (obj == null) throw new System.ArgumentNullException("obj");
        obj.MouseRightButtonDown += OnMouseRightButtonDown;
    }

    private void OnMouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {
        ExecuteCommand();
    }       
}

另一堂课:

 public class MouseRightButtonDown
{
    private static readonly DependencyProperty MouseRightButtonDownCommandBehaviorProperty = DependencyProperty.RegisterAttached(
        "MouseRightButtonDownCommandBehavior",
        typeof(UIElementMouseRightButtonDownCommandBehavior),
        typeof(MouseRightButtonDown),
        null);

    public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(
        "Command",
        typeof(ICommand),
        typeof(MouseRightButtonDown),
        new PropertyMetadata(OnSetCommandCallback));

    public static void SetCommand(UIElement element, ICommand command)
    {
        element.SetValue(CommandProperty, command);
    }

    public static ICommand GetCommand(UIElement element)
    {
        return element.GetValue(CommandProperty) as ICommand;
    }

    private static void OnSetCommandCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
    {
        UIElement element = dependencyObject as UIElement;
        if (element != null)
        {
            UIElementMouseRightButtonDownCommandBehavior behavior = GetOrCreateBehavior(element);
            behavior.Command = e.NewValue as ICommand;
        }
    }

    private static UIElementMouseRightButtonDownCommandBehavior GetOrCreateBehavior(UIElement element)
    {
        UIElementMouseRightButtonDownCommandBehavior behavior = element.GetValue(MouseRightButtonDownCommandBehaviorProperty) as UIElementMouseRightButtonDownCommandBehavior;
        if (behavior == null)
        {
            behavior = new UIElementMouseRightButtonDownCommandBehavior(element);
            element.SetValue(MouseRightButtonDownCommandBehaviorProperty, behavior);
        }
        return behavior;
    }
}

然后在您的视图模型文件中:

public ICommand SelectNameCommand
    {
        get { return new Command(P => SelectName()); }
    }

我认为您的XAML是正确的。