WPF附加属性关闭窗口并在ViewModel中对其执行操作

时间:2014-10-05 12:05:18

标签: c# wpf mvvm attached-properties

我正在尝试将Window Closed事件重定向到我的ViewModel,但缺乏对AttachedProperties的正确实践经验。

包含AttachedProperty

的类
public class WindowClosedBehavior
{
    public static readonly DependencyProperty ClosedProperty = DependencyProperty.RegisterAttached(
        "Closed",
        typeof (ICommand),
        typeof (WindowClosedBehavior),
        new UIPropertyMetadata(ClosedChanged));

    private static void ClosedChanged(
        DependencyObject target,
        DependencyPropertyChangedEventArgs e)
    {
        var window = target as Window;

        if (window != null)
        {
            // ??
        }
    }

    public static void SetClosed(Window target, ICommand value)
    {
        target.SetValue(ClosedProperty, value);
    }
}

如何实现该行为以便关闭窗口并触发RelayCommand


(剥离的)ViewModel:

    public RelayCommand WindowClosedCommand { get; private set; }

    public MainCommandsViewModel()
    {
        WindowClosedCommand = new RelayCommand(WindowClosedCommandOnExecuted, WindowClosedCommandOnCanExecute);
    }

MainWindow.xaml

<Window x:Class="TvShowManager.UserInterface.Views.MainWindow"

        <!-- left out irrelevant parts -->
        xmlns:closeBehaviors="clr-namespace:TvShowManager.UserInterface.CloseBehaviors"
        closeBehaviors:WindowClosedBehavior.Closed="{Binding WindowCloseCommand}" >

我只需将RelayCommand(WindowCloseCommand)绑定到附加属性。


我尝试通过这个进行调试以获得更好的理解,并希望弄清楚如何继续,但是没有断点在包含我附属属性的类中被击中。如果有人能解释为什么WindowClosedBehavior中的代码永远不会被执行,我也非常感谢那里的建议。

我希望我很清楚我想要实现的目标,并且有人可以帮助我。

非常感谢

1 个答案:

答案 0 :(得分:2)

ClosedChanged回调中,只需存储命令并向窗口的Closed事件注册事件处理程序以调用命令:

private static ICommand _command;

private static void ClosedChanged(
    DependencyObject target,
    DependencyPropertyChangedEventArgs e)
    {
        var window = target as Window;

        if (window != null)
        {
            _command = e.NewValue as ICommand;
            window.Closed += (sender, args) =>
            {
                if (_command != null)
                    _command.Execute(null);
            }
        }
    }

此外,您可能希望在窗口的Closed事件中取消注册所有以前存在的事件处理程序,但只有在计划在运行时更改WindowClosedBenahior时才需要这样做。