しょっぱい小技です。
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してください。
<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>