【WPF】Visibilityへのバインドで表示/非表示を制御する
表示、非表示を制御するのにVisibilityを使う方法があるけれど、ViewModelで設定したbool型をバインドするだけだとうまくいかない。
BooleanToVisibilityConverterも使ってバインドがうまくいく
■MainWindow.xaml <Window x:Class="MyWorkProject.Views.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:prism="http://prismlibrary.com/" prism:ViewModelLocator.AutoWireViewModel="True" Title="{Binding Title}" Height="350" Width="525"> <Window.Resources> <BooleanToVisibilityConverter x:Key="BoolVisibilityConverter" ></BooleanToVisibilityConverter> </Window.Resources> <Grid> <StackPanel> <Button Content="ボタンA" Visibility="{Binding ButtonAVisibled, Converter={StaticResource BoolVisibilityConverter}}"/> <Button Content="ボタンB" Visibility="{Binding ButtonBVisibled, Converter={StaticResource BoolVisibilityConverter}}"/> <ContentControl prism:RegionManager.RegionName="ContentRegion" /> </StackPanel> </Grid> </Window>
■MainWindowViewModel.cs using Prism.Mvvm; namespace MyWorkProject.ViewModels { public class MainWindowViewModel : BindableBase { private string _title = "Prism Application"; public string Title { get { return _title; } set { SetProperty(ref _title, value); } } private bool _buttonAVisibled; public bool ButtonAVisibled { get { return _buttonAVisibled; } set { SetProperty(ref _buttonAVisibled, value); } } private bool _buttonBVisibled; public bool ButtonBVisibled { get { return _buttonBVisibled; } set { SetProperty(ref _buttonBVisibled, value); } } public MainWindowViewModel() { ButtonAVisibled = true; ButtonBVisibled = false; } } }