Label Visibility.Collapsed在空内容WPF MVVM上

时间:2016-03-12 19:21:41

标签: c# wpf xaml mvvm

我试图弄清楚当隐藏标签时我如何隐藏标签&使用XAML设置文本时再次可见。我可以使用TextChanged事件轻松完成,但必须有一个正确的方法来使用xaml,对吗?

我完成了我的研究,但我找不到任何有用的东西。

窗口1

<TextBox Name="nameTxt" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />

窗口2

<Label Name="nameLbl" Content="{Binding Name}" />

2 个答案:

答案 0 :(得分:1)

添加自定义转换器。

wpf tutorial value converters

您可以编写逻辑来测试string.IsNullOrEmpty并返回hidden,否则返回可见。

这种方法很不错,因为它可以保持视图模型的可见性。

答案 1 :(得分:1)

基本上它是由.Net BooleanToVisibilityConverter中的内置类实现的:

<UserControl.Resources>
    <BooleanToVisibilityConverter x:Key="booleanVisibilityConverter"/>
</UserControl.Resources>

让我展示工作示例:

XAML:

<Button Content="Hello, I am the button" Visibility="{Binding ShowButton, 
   Converter={StaticResource booleanVisibilityConverter}}"/>

视图模型:

private bool _showButton = false;
public bool ShowButton
{
   get { return _showButton; }
   set
   {
      if (value != _showButton)
      {
         _showButton = value;
         OnPropertyChanged("ShowButton");
      }
   }
}

如果您想在代码中更改按钮的Visibility,可以通过ViewModel中的此代码进行操作:

IsButtonVisible = false;