LoginSignup
2
0

More than 5 years have passed since last update.

WPFでWindowのCloseをプロパティ化する

Last updated at Posted at 2017-01-31

Windowを継承してIsOpenプロパティを実装したWindowExを作成する

    public class WindowEx : Window
    {
        public static readonly DependencyProperty IsOpenProperty = DependencyProperty.Register(
            "IsOpen", typeof(bool), typeof(WindowEx), new PropertyMetadata(default(bool)));

        public bool IsOpen
        {
            get { return (bool)GetValue(IsOpenProperty); }
            set { }
        }

        protected override void OnContentRendered(EventArgs e)
        {
            base.OnContentRendered(e);
            SetValue(IsOpenProperty, true);
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            SetValue(IsOpenProperty, false);
        }
    }

Windowの継承元はWindowExに置き換えるてIsOepnプロパティをBind設定する

    public partial class MainWindow : WindowEx
    {
        public MainWindow()
        {
            InitializeComponent();       

        }        
    }
<local:WindowEx x:Class="WpfApplication1.MainWindow"
        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:WpfApplication1"
        mc:Ignorable="d" IsOpen="{Binding IsOpen.Value , Mode=OneWayToSource}"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:MainWindowViewModel />
    </Window.DataContext>
    <Grid>

    </Grid>
</local:WindowEx>

ViewModelクラス

    public class MainWindowViewModel
    {
        public MainWindowViewModel()
        {
            IsOpen.Subscribe(x =>
            {
                Debug.WriteLine(x);
            });
        }

        public ReactiveProperty<bool> IsOpen { get; set; } =
            new ReactiveProperty<bool>();
    }
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0