繁体   English   中英

在WPF-MVVM中保存并关闭在当前窗口中

[英]Save and Close in Current Window in WPF-MVVM

我的窗口中有两个按钮,保存,保存和关闭。 如果用户单击“保存”,则可以成功保存详细信息。 当用户单击“保存并关闭”时,我无法弄清楚如何关闭窗口。 这是我保存的代码

<telerik:RadButton x:Name="button_Save" Content="Save" Command="{Binding SaveProductCommand}" CommandParameter="{Binding ElementName=ProductName, Path=Text}" />

这是我的中继命令。

public ICommand SaveProductCommand
{
  get 
  {
    return new RelayCommand<string>(SaveProductExecute);
  } 
 }

我的第一个问题:

我们可以为Save和Save&Close再传递一个参数True或false吗? 这样我们就只能对两者使用一个中继命令?

第二个问题:

保存后如何关闭当前窗口?

很好的问题..这里的关键是使用Action 。看看我的示例

我们将尽量减少编码。

我们可以为Save和Save&Close再传递一个参数True或false吗? 这样我们就只能对两者使用一个中继命令?

由于您还没有提到如何传递true或false,所以我包括了一个列表框,其中包含两个字符串项TrueFalse

如果选择true则仅执行命令的一部分;如果选择false则将执行命令中的两种方法。

  1. 使用按钮列表框创建视图

      <ListBox x:Name="items"> <System:String>True</System:String> <System:String>False</System:String> </ListBox> <Button Content="MyButton" Command="{Binding Path=MyCustomCommand}" CommandParameter="{Binding SelectedItem,ElementName=items}"/> 
  2. 创建ViewModel即MyViewModel.cs

     public class MyViewModel : INotifyPropertyChanged { public Action CloseAction { get; set; } public ICommand MyCustomCommand { get; set; } public MyViewModel() { MyCustomCommand = new RelayCommand(new Action<object>(MyFunction)); } private void MyFunction(object MyCommandParameter) { if (Convert.ToString(MyCommandParameter) == "True") { MessageBox.Show("Save Executed"); } else { MessageBox.Show("Save Execcuted"); CloseAction(); } } 
  3. 在代码背后

      public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); MyViewModel mv = new MyViewModel(); this.DataContext = mv; if (mv.CloseAction == null) mv.CloseAction = new Action(() => this.Close()); } } 

回答您的2个问题-

是的,你可以多重绑定...做这样的事情..

<Button.CommandParameter>
    <MultiBinding>
         <Binding Path="path" ElementName="elementName"/>
         <Binding Path="path2" ElementName="elementName2"/>
    </MultiBinding>
</Button.CommandParameter>

有很多关闭窗口的方法,请在这里这里看看

考虑利用带参数的消息传递在对象之间传递数据。

您可以使用EventAggregatorMessageBus

想法是让您的用户控件订阅他们想要响应的事件。

注意:

我用viewmodels做到这一点。 但是,我认为在将此代码添加到旨在具有普遍用途的用户控件时,这是一种代码气味,而与使用它们的应用程序无关。

我将“ 发布订阅”模式用于复杂的类相关性:

视图模型:

    public class ViewModel : ViewModelBase
    {
        public ViewModel()
        {
            CloseComand = new DelegateCommand((obj) =>
                {
                    MessageBus.Instance.Publish(Messages.REQUEST_DEPLOYMENT_SETTINGS_CLOSED, null);
                });
        }
}

窗口:

public partial class SomeWindow : Window
{
    Subscription _subscription = new Subscription();

    public SomeWindow()
    {
        InitializeComponent();

        _subscription.Subscribe(Messages.REQUEST_DEPLOYMENT_SETTINGS_CLOSED, obj =>
            {
                this.Close();
            });
    }
}

您可以利用Bizmonger.Patterns获取MessageBus。

MessageBus

public class MessageBus
{
    #region Singleton
    static MessageBus _messageBus = null;
    private MessageBus() { }

    public static MessageBus Instance
    {
        get
        {
            if (_messageBus == null)
            {
                _messageBus = new MessageBus();
            }

            return _messageBus;
        }
    }
    #endregion

    #region Members
    List<Observer> _observers = new List<Observer>();
    List<Observer> _oneTimeObservers = new List<Observer>();
    List<Observer> _waitingSubscribers = new List<Observer>();
    List<Observer> _waitingUnsubscribers = new List<Observer>();

    int _publishingCount = 0;
    #endregion

    public void Subscribe(string message, Action<object> response)
    {
        Subscribe(message, response, _observers);
    }

    public void SubscribeFirstPublication(string message, Action<object> response)
    {
        Subscribe(message, response, _oneTimeObservers);
    }

    public int Unsubscribe(string message, Action<object> response)
    {
        var observers = new List<Observer>(_observers.Where(o => o.Respond == response).ToList());
        observers.AddRange(_waitingSubscribers.Where(o => o.Respond == response));
        observers.AddRange(_oneTimeObservers.Where(o => o.Respond == response));

        if (_publishingCount == 0)
        {
            observers.ForEach(o => _observers.Remove(o));
        }

        else
        {
            _waitingUnsubscribers.AddRange(observers);
        }

        return observers.Count;
    }

    public int Unsubscribe(string subscription)
    {
        var observers = new List<Observer>(_observers.Where(o => o.Subscription == subscription).ToList());
        observers.AddRange(_waitingSubscribers.Where(o => o.Subscription == subscription));
        observers.AddRange(_oneTimeObservers.Where(o => o.Subscription == subscription));

        if (_publishingCount == 0)
        {
            observers.ForEach(o => _observers.Remove(o));
        }

        else
        {
            _waitingUnsubscribers.AddRange(observers);
        }

        return observers.Count;
    }

    public void Publish(string message, object payload)
    {
        _publishingCount++;

        Publish(_observers, message, payload);
        Publish(_oneTimeObservers, message, payload);
        Publish(_waitingSubscribers, message, payload);

        _oneTimeObservers.RemoveAll(o => o.Subscription == message);
        _waitingUnsubscribers.Clear();

        _publishingCount--;
    }

    private void Publish(List<Observer> observers, string message, object payload)
    {
        Debug.Assert(_publishingCount >= 0);

        var subscribers = observers.Where(o => o.Subscription.ToLower() == message.ToLower());

        foreach (var subscriber in subscribers)
        {
            subscriber.Respond(payload);
        }
    }

    public IEnumerable<Observer> GetObservers(string subscription)
    {
        var observers = new List<Observer>(_observers.Where(o => o.Subscription == subscription));
        return observers;
    }

    public void Clear()
    {
        _observers.Clear();
        _oneTimeObservers.Clear();
    }

    #region Helpers
    private void Subscribe(string message, Action<object> response, List<Observer> observers)
    {
        Debug.Assert(_publishingCount >= 0);

        var observer = new Observer() { Subscription = message, Respond = response };

        if (_publishingCount == 0)
        {
            observers.Add(observer);
        }
        else
        {
            _waitingSubscribers.Add(observer);
        }
    }
    #endregion
}

}

订阅

public class Subscription
{
    #region Members
    List<Observer> _observerList = new List<Observer>();
    #endregion

    public void Unsubscribe(string subscription)
    {
        var observers = _observerList.Where(o => o.Subscription == subscription);

        foreach (var observer in observers)
        {
            MessageBus.Instance.Unsubscribe(observer.Subscription, observer.Respond);
        }

        _observerList.Where(o => o.Subscription == subscription).ToList().ForEach(o => _observerList.Remove(o));
    }

    public void Subscribe(string subscription, Action<object> response)
    {
        MessageBus.Instance.Subscribe(subscription, response);
        _observerList.Add(new Observer() { Subscription = subscription, Respond = response });
    }

    public void SubscribeFirstPublication(string subscription, Action<object> response)
    {
        MessageBus.Instance.SubscribeFirstPublication(subscription, response);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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