BooleanToVisibilityConverter
bool型をVisibilityに変換するコンバーターとしてBooleanToVisibilityConverterというものがあります。
以下のようにWindow.Resouceに宣言することで、ViewModelなどに定義したbool型のIsVisiblie
プロパティをVisibilityに変換し、バインドすることができます。
MainWindow.xaml
<Window x:Class="SampleWpf.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"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="300">
<Window.Resource>
<BooleanToVisibilityConverter x:Key="Bool2Visibility"/>
</Window.Resource>
<Grid HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock FontSize="20"
Text="Text"
Visibility="{Binding IsVisible, Converter={StaticResource Bool2Visibility}, Mode=OneWay}"/>
</Grid>
</Window>
WindowクラスのVisibilityにバインドする
上記で示した方法だと、Windowの子要素にあたるコントロールには宣言したBool2Visibility
を使用することができますが、Windowクラス自体のプロパティには使用することができません。
Windowのプロパティでも使用したい場合はWindowの親にあたるApp.xaml
に宣言を記載する必要があります。(Windowに限らず、親で宣言されたコントロールが使用できると思われます。)
App.xaml
<Application x:Class="SampleWpf.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SampleWpf"
StartupUri="MainWindow.xaml">
<Application.Resources>
<BooleanToVisibilityConverter x:Key="Bool2Visibility"/>
</Application.Resources>
</Application>
下記のようにWindowクラスにbool型のIsWindowVisible
プロパティをコンバートしてバインドできます。
※ WindowのVisibilityを動的に変更しようとすると、Mode=TwoWay
でバインドしないとうまく動作しませんでした。(バインディングが外れている?)
MainWindow.xaml
<Window x:Class="SampleWpf.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"
mc:Ignorable="d"
Visibility="{Binding IsWindowVisible, Converter={StaticResource Bool2Visibility}, Mode=TwoWay}"
Title="MainWindow" Height="200" Width="300">
...
</Window>