LoginSignup
4
3

More than 5 years have passed since last update.

Visibilityを変更するボタン

Posted at

しょっぱい小技です。
MVVMで作っていて、表示をON/OFFするボタンが面倒になったので作りました。
どうせ探せばあるのでしょう。はいはい車輪の再発明。

ChangeVisibilityButton.cs
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace MySilverlightLibrary.Control
{
    public class ChangeVisibilityButton:Button
    {
        public FrameworkElement TargetElement
        {
            get { return (FrameworkElement)GetValue(TargetElementProperty); }
            set { SetValue(TargetElementProperty, value); }
        }

        // Using a DependencyProperty as the backing store for TargetElement.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TargetElementProperty =
            DependencyProperty.Register("TargetElement", typeof(FrameworkElement), typeof(ChangeVisibilityButton), new PropertyMetadata(null));

        public ChangeVisibilityButton()
        {
            this.Click += ChangeVisibilityButton_Click;
        }

        void ChangeVisibilityButton_Click(object sender, RoutedEventArgs e)
        {
            if( TargetElement !=null)
            {
                if(TargetElement.Visibility == System.Windows.Visibility.Visible)
                {
                    TargetElement.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    TargetElement.Visibility = System.Windows.Visibility.Visible;
                }
            }
        }

    }
}

使い方
TargetElementに対象をBindingしてください。
xml
<Grid x:Name="LayoutRoot">
<StackPanel>
<my:ChangeVisibilityButton Width="100" Height="30" Content="test" TargetElement="{Binding ElementName=test}"></my:ChangeVisibilityButton>
<Button Name="test" Height="50" Background="Aqua" Foreground="AliceBlue"></Button>
</StackPanel>
</Grid>

4
3
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
4
3