简体   繁体   中英

wpf - One ViewModel that interacts with multiple instances of a Model

I have a WorkspaceViewModel that handles addition and deletion of tab items dynamically through an ObservableCollection. Each time a tab is connected to a PayslipModel, all bindings work fine but one problem I am having is that;

I have a save button in the UserControl who's DataContext is set to WorkspaceViewModel and I would like to save whatever info is being displayed in the selected tab. Now, each time a tab is added, a new instance of PayslipModel is created, which is exactly what I want because I don't want bindings to be shared for all tabs. However, I am unable to save what is being displayed since PayslipModel has multiple instances, therefore nothing is returned (temporarily using MessageBox to test if info is being retrieved) when I hit save.

I created a diagram to better explain my situation: 在此处输入图片说明

Is it possible to access the current instance when a tab is selected or cycle through all instances and do something like batch saving?

This is a working example which shows one of the possiblities:

View

    <TabControl DataContext="{Binding}" ItemsSource="{Binding Models}"  >
        <TabControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}" > 
                </TextBlock>
            </DataTemplate>
        </TabControl.ItemTemplate>
        <TabControl.ContentTemplate>
            <DataTemplate>
                <DockPanel>
                    <Button DockPanel.Dock="Top" Content="Click Me" Command="{Binding DataContext.PCommand, 
                                                            RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=TabControl}}"
                            CommandParameter="{Binding Desc}"/>
                    <TextBlock Text="{Binding Desc}" >
                    </TextBlock>
                </DockPanel> 
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>

Model View

public class ModelView
{
    public ModelView()
    {
        _models = new ObservableCollection<Model>(); 
        _pCommand = new Command(DoParameterisedCommand);
    }
    ObservableCollection<Model> _models;
    public ObservableCollection<Model> Models { get { return _models; } }

    private void DoParameterisedCommand(object parameter)
    {
        MessageBox.Show("Parameterised Command; Parameter is '" +
                     parameter.ToString() + "'.");
    }
    Command _pCommand;
    public Command PCommand
    {
        get { return _pCommand; }
    }
}

Model

public class Model : INotifyPropertyChanged
{
    string _desc;
    public string Desc { get { return _desc; } set { _desc = value; RaisePropertyChanged("Desc"); } }

    string _name;
    public string Name { get { return _name; } set { _name = value; RaisePropertyChanged("Name"); } }

    public event PropertyChangedEventHandler PropertyChanged;
    void RaisePropertyChanged(string propname)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propname));
    }
}

Command

public class Command : ICommand
{ 
    public Command(Action<object> parameterizedAction, bool canExecute = true)
    {
        _parameterizedAction = parameterizedAction;
        _canExecute = canExecute;
    }


    Action<object> _parameterizedAction = null;
    bool _canExecute = false;
    public bool CanExecute
    {
        get { return _canExecute; }
        set
        {
            if (_canExecute != value)
            {
                _canExecute = value;
                CanExecuteChanged?.Invoke(this, EventArgs.Empty);
            }
        }
    }
    public event EventHandler CanExecuteChanged;
    bool ICommand.CanExecute(object parameter)
    {
        return _canExecute;
    }

    void ICommand.Execute(object parameter)
    {
        this.DoExecute(parameter);
    }
    public virtual void DoExecute(object param)
    { if (_parameterizedAction != null)
            _parameterizedAction(param);
        else
            throw new Exception();
    }


}

Use this to initialize:

    public MainWindow()
    {
        InitializeComponent();
        ModelView mv = new ModelView();
        mv.Models.Add(new Model() { Name = "a", Desc = "aaa" });
        mv.Models.Add(new Model() { Name = "b" , Desc = "bbb"});
        mv.Models.Add(new Model() { Name = "c", Desc = "cccc" });
        this.DataContext = mv; 

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM