绑定ViewModel命令到另一个窗口视图?

时间:2019-07-03 18:25:40

标签: c# wpf mvvm

我的ListBox中有一个UserControl,它显示在主窗口中。我在主窗口的ViewModel包含两个ICommand,分别从列表框中删除和添加。我已成功将删除命令从主窗口绑定到列表框。但是,我有一个从主窗口打开的单独窗口,其中包括一个向列表框中添加ListBoxItem的按钮。我的主窗口ViewModel在第二个窗口的上下文中不存在。我无法实例化另一个ViewModel,因为它将不包含ViewModel中我的ObservableCollection中已经存在的项。

我该如何以MVVM方法解决此问题?我应该为第二个窗口视图创建另一个ViewModel吗?如果是这样,我如何确保所有现有的ListBoxItem对它都是可见的?

更新:根据要求,最少的代码。

包含我的列表框的我的UserControl:

<UserControl>  
    <Grid>
        <StackPanel>
            <ListBox x:Name="lstBox" ItemsSource="{Binding myList}" DisplayMemberPath="Desc">
            </ListBox>
            <Button x:Name="btn_Remove" Content="Remove" Command="{Binding RemoveCommand}" 
                    CommandParameter="{Binding ElementName=lstBox, Path=SelectedIndex}"/>
        </StackPanel>
    </Grid>
</UserControl>

包含ICommands的MainWindow ViewModel:

  public class MainWindowViewModel {

      private RelayCommand removeCommand;
      private RelayCommand addCommand;

      public ObservableCollection<myObjModel> MyList {
          get;
          set;
      }

      public void createList() {
          ObservableCollection<myObjModel> myList = new ObservableCollection<myObjModel>();
          myList.Add(new myObjModel { Desc = "test" });
          MyList = myList;
      }

      public ICommand RemoveCommand {
          get {
              if (removeCommand == null) {
                  removeCommand = new RelayCommand(param => remove((int)param));
              }
              return removeCommand;
          }
      }

      public void remove(int i) {
          MyList.RemoveAt(i);
      }

      public ICommand AddCommand {
          get {
              if (addCommand == null) {
                  addCommand = new RelayCommand(param => add((string)param));
              }
              return addCommand;
          }
      }

      public void add(string desc) {
          Telegrams.Add(new TelegramyObjModelmModel { Desc = desc });
      }
 }

我的MainWindow XAML:

<Window
xmlns:uc="clr-namespace:myClass">
    <Grid>
        <uc:UserControl x:Name="myUserControl" Loaded="myUserControl_Loaded"/>
    </Grid>
</Window>

后面的代码

    public partial class MainWindow : Window {

    MainWindowViewModel ViewModelObject;

           public MainWindow() {
            InitializeComponent();
        }

            private void myUsereControl_Loaded(object sender, RoutedEventArgs e) {
            ViewModelObject = new MainWindowViewModel();
            ViewModelObject.createList();
            myUsereControl_Loaded.DataContext = ViewModelObject;
        }
      }

0 个答案:

没有答案