【问题标题】:MVVM good practice?MVVM 的好习惯?
【发布时间】:2014-11-14 06:29:12
【问题描述】:

我有一个 treeView(FunctionTreeView) 并且想在 View 和 ViewModel 之间交换数据。

这是我的观点

private void FunctionTreeView_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
    {
        TreeViewItem parent;
        int pIndex,cIndex = 0;
        if (e.Key == Key.Enter)
            EnteredKeys.Length = 0;
        else
            EnteredKeys.Append(e.Key.ToString());

        if (FunctionTreeView.Items.IndexOf(FunctionTreeView.SelectedItem) != -1)
        {
            //if selected is parent, get parent item. 
            parent = FunctionTreeView.Tag as TreeViewItem;
            cIndex = -1;
        }
        else
        {
            TreeViewItem child = FunctionTreeView.Tag as TreeViewItem;
            parent = ItemsControl.ItemsControlFromItemContainer(child) as TreeViewItem;
            cIndex = parent.ItemContainerGenerator.IndexFromContainer(child);
        }

        pIndex = FunctionTreeView.ItemContainerGenerator.IndexFromContainer(parent);
        ViewModel.PerformSearch(pIndex,cIndex);

PerformSearch 函数驻留在 ViewModel 中。在视图中访问这样的 UI 元素是一种好的做法/最好的方法吗?我是 MVVM 的新手。

【问题讨论】:

  • 不,不是。看看commands
  • 但是我不能通过命令传递值,对吧?
  • 你可以。您需要为此使用CommandParameter,它将作为参数传递给ICommand.Execute
  • @SriramSakthivel 非常感谢。

标签: c# wpf mvvm treeview


【解决方案1】:
public class RelayCommand : ICommand
{
    //Your Code
}

阅读以下链接。它会帮助你。

Basic MVVM and ICommand usuage example

Commands in MVVM

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-17
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多