更好的方式和更动态的是:
您可以创建一个 bool 属性并将可见性按钮绑定到它,如下所示:
bool IsVisible { get; set; } //Code behind
在 xaml 中:
<!-- Pay attention: The Converter is still not written, follow next steps -->
<Button x:Name="DeleteButton"
Content="Delete"
HorizontalAlignment="Left" Height="64" Margin="74,579,0,-9"
VerticalAlignment="Top" Width="314" FontSize="24"
Visibility="{Binding IsVisible,
Converter={StaticResource BooleanToVisibilityConverter}}" />
转换器:
public class BooleanToVisibilityConverter : IValueConverter
{
/// <summary>
/// Converts a value.
/// </summary>
/// <param name="value">The value produced by the binding source.</param>
/// <param name="targetType">The type of the binding target property.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>A converted value. Returns Visible if the value is true; otherwise, collapsed.</returns>
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 中的资源中,您应该添加转换器,以便您可以使用 StaticResource 访问它:
<Application
x:Class="UI.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converters="using:UI.Converters">
<converters:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
然后根据需要更改 IsVisible 属性,如果为 true,它将绑定到 Visible,如果为 false,它将被折叠。
if (condition)
{
IsVisible = true;
}
如需了解更多信息,您应该了解:binding、converters。