标签不为空时隐藏按钮

时间:2012-10-25 02:23:07

标签: c# wpf

我正在使用WPF。

我想在标签不为空时显示按钮。当Label有一个值时,该按钮将被隐藏。

如何使用WPF执行此操作?使用<Style>

代码:

<Label Name="lblCustomerName"/>
<Button Name="btnCustomer" Content="X" Visibility="Hidden" />

2 个答案:

答案 0 :(得分:2)

尝试


if (string.IsNullOrEmpty(lblCustomerName.Text)) { 
    btnCustomer.Visibility = Visibility.Hidden;
} 
else {
    btnCustomer.Visibility = Visibility.Visible;
}

答案 1 :(得分:1)

您需要使用转换器并将其绑定到lblCustomer的内容。

public class ContentNullToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
        {
            return Visibility.Hidden;
        }
        return Visibility.Visible;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

有关转换器的更多信息here

然后在xaml中,您可以执行以下操作:

需要在资源中定义第一行,您需要使用您在其中创建上述类的命名空间来限定它。一旦定义了资源,就可以使用第二部分。

<ContentNullToVisibilityConverter x:Key="visConverter"/>

<Label Name="lblCustomerName"/>
<Button Name="btnCustomer" Content="X" Visibility="{Binding ElementName=lblCustomer, Path=Content, Converter={StaticResource visConverter}}" />
相关问题