我在WPF应用程序中有启动窗口,我在我的视图中有这个代码:
<Window x:Class="MyView"
Name="ucPrincipal"
Title="{Binding Titulo}"
Visibility="{Binding EsUpdaterVisible, Mode=TwoWay}">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="../Recursos/Diccionarios/Converters.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Button Content="Aceptar" HorizontalAlignment="Left" Margin="10,145,0,0" VerticalAlignment="Top" Width="75">
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewMouseLeftButtonDown">
<cmd:EventToCommand Command="{Binding AceptarCommand}" PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
我的ViewModel:
private RelayCommand _aceptarCommand;
public RelayCommand AceptarCommand
{
get { return _aceptarCommand ?? (_aceptarCommand = new RelayCommand(aceptarCommand)); }
}
private void aceptarCommand()
{
try
{
EsUpdaterVisible = false;
Titulo = "Después de aceptar.";
}
catch { throw; }
}
private bool _esUpdaterVisible = true;
public bool EsUpdaterVisible
{
get { return _esUpdaterVisible; }
set
{
if (_esUpdaterVisible != value)
{
_esUpdaterVisible = value;
base.RaisePropertyChangedEvent("EsUpdaterVisible");
}
}
}
private string _titulo = "Inicio";
public string Titulo
{
get { return _titulo; }
set
{
if (_titulo != value)
{
_titulo = value;
base.RaisePropertyChangedEvent("Titulo");
}
}
}
单击“aceptar”按钮时,窗口标题会发生变化,但窗口仍然可见。
我想在某些情况下从视图模型中隐藏窗口。我怎么能这样做?
感谢。
答案 0 :(得分:2)
如果您不想使用转换器,只需使用xaml part:
<Window x:Class="MyView"
Name="ucPrincipal"
Title="{Binding Titulo}">
<Window.Style>
<Style TargetType="Window">
<Style.Triggers>
<DataTrigger Binding="{Binding EsUpdaterVisible,UpdateSourceTrigger=PropertyChanged}" Value="True">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
<DataTrigger Binding="{Binding EsUpdaterVisible,UpdateSourceTrigger=PropertyChanged}" Value="False">
<Setter Property="Visibility" Value="Collapsed"/> <!-- use hide instead of collapsed if you would like to open again this instance of window after close. -->
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Style>
答案 1 :(得分:1)
可见性不是布尔类型。 您可以使用转换器来实现这一目标。 转换器:
[ValueConversion(typeof(bool), typeof(Visibility))]
public class VisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (bool)value ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
比你的XAML看起来像这样:
<Window x:Class="MyView"
Name="ucPrincipal"
Title="{Binding Titulo}"
Visibility="{Binding EsUpdaterVisible, Converter={StaticResource visibilityConverter}}">