Hi Sarah,
I cannot reproduce your problem with following code:
XAML:
<Window x:Class="WpfApp1.Window008"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp008"
mc:Ignorable="d"
Title="Window008" Height="450" Width="800"
local:ViewModel.AttProp="True">
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<StackPanel>
<Button Content="Change" Command="{Binding}" Width="200"/>
</StackPanel>
</Window>
ViewModel:
using System;
using System.Windows;
using System.Windows.Input;
namespace WpfApp008
{
public class ViewModel : ICommand
{
public Window Wnd;
public event EventHandler? CanExecuteChanged;
public bool CanExecute(object? parameter) => true;
public void Execute(object? parameter)
{
if (Wnd == null) return;
if (Wnd.WindowState == WindowState.Normal) Wnd.WindowState = WindowState.Maximized;
else if (Wnd.WindowState == WindowState.Maximized) Wnd.WindowState = WindowState.Normal;
}
#region attached property
public static readonly DependencyProperty AttPropProperty =
DependencyProperty.RegisterAttached("AttProp", typeof(bool), typeof(ViewModel), new PropertyMetadata(false, OnPropChanged));
public static bool GetAttProp(DependencyObject obj) => (bool)obj.GetValue(AttPropProperty);
public static void SetAttProp(DependencyObject obj, bool par) => obj.SetValue(AttPropProperty, par);
private static void OnPropChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Window w = d as Window;
if (w == null) return;
w.Loaded += (s, mbe) => ((ViewModel)(w.DataContext)).Wnd = w;
}
#endregion
}
}
Result: