0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【WPF】WindowクラスのVisibilityにBooleanをコンバートしてバインドする

Posted at

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>
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?