为Caliburn管理窗口始终启用顶部

时间:2012-07-30 21:00:12

标签: caliburn.micro

我有以下ViewModel,我正在使用Caliburn Micro。 IWindowManager实例已正确解析,所有代码都可以正常工作。正如TODO评论所示,我需要获得对当前窗口的引用,以便我可以切换AlwaysOnTop属性。我怎么能这样做?

namespace CaliburnWizardPlay
{
[Export(typeof(DropWindowViewModel))]
public class DropWindowViewModel : PropertyChangedBase, IHaveDisplayName
{
    private readonly IWindowManager windowManager;

    [ImportingConstructor]
    public DropWindowViewModel(IWindowManager windowManager)
    {
        this.windowManager = windowManager;
    }

    public string DisplayName
    {
        get { return "Main Window"; }
        set { }
    }        

    public bool AlwaysOnTop
    {
        get { return Settings.Default.DropWindowAlwaysOnTop; }
        set
        {
            Settings.Default.DropWindowAlwaysOnTop = value;
            Settings.Default.Save();
            NotifyOfPropertyChange(() => AlwaysOnTop);
            //todo: toggle the AOT attribute of the window
        }
    }

    public void FileDropped(DragEventArgs eventArgs)
    {
        if (eventArgs.Data.GetDataPresent(DataFormats.FileDrop))
        {
            string[] droppedFilePaths = eventArgs.Data.GetData(DataFormats.FileDrop, true) as string[];
            foreach (string path in droppedFilePaths)
            {
                MessageBox.Show(path);
            }

            windowManager.ShowWindow(new WizardViewModel());
        }
    }

}

}

1 个答案:

答案 0 :(得分:3)

您可以使用settings方法的ShowWindow参数在创建的窗口中使用包含propertyname-value对的字典设置任何属性(例如Topmost):

 
windowManager.ShowWindow(new WizardViewModel(), 
    settings: new Dictionary<string,object> { {"Topmost", AlwaysOnTop} });

如果您想更改已创建窗口的Topmost属性,我会看到三个选项(按优先顺序排列):

  1. AlwaysOnTop上创建WizardViewModel属性,并将viewmodel存储在私有字段中,并将AlwaysOnTop委托给WizardViewModel

    private WizardViewModel wizardViewModel;
    
    public void FileDropped(DragEventArgs eventArgs)
    {
        //...
        wizardViewModel = new WizardViewModel()
        windowManager.ShowWindow(wizardViewModel);
    }
    
    public bool AlwaysOnTop
    {
         get { return Settings.Default.DropWindowAlwaysOnTop; }
         set
         {
             //...
             if (wizardViewModel != null)
                 wizardViewModel.AlwaysOnTop = value;
         }
    }
    

    在您的视图中,您可以将WizardViewModel的{​​{1}}属性绑定到窗口的AlwaysOnTop属性。

  2. 您可以使用Application.Windows来检索窗口。例如。使用设置字典设置创建的Window的TopMost属性,然后:

    Name
  3. windowManager.ShowWindow(new WizardViewModel(), settings: new Dictionary<string,object> { {"Topmost", AlwaysOnTop}, {"Name", "WizardWindow"} }); public bool AlwaysOnTop { get { return Settings.Default.DropWindowAlwaysOnTop; } set { //... var wizardViewModel = Application.Current.Windows.OfType<Window>() .SingleOrDefault(w => w.Name == "WizardWindow"); if (wizardViewModel != null) wizardViewModel.AlwaysOnTop = value; } } 导出并在WindowManager中注册,然后您可以覆盖BootstrapperCreateWindow等方法,将创建的窗口存储在某处设置其他属性等。