我有一个按钮,名为删除。 我只是想让只有当某些条件得到满足, 所以我怎么能做到这一点?如何在windows phone中以编程方式制作按钮?
的按钮创建的XAML代码是
<Button x:Name="DeleteButton" Content="Delete" HorizontalAlignment="Left" Height="64" Margin="74,579,0,-9" VerticalAlignment="Top" Width="314" FontSize="24"/>
我有一个按钮,名为删除。 我只是想让只有当某些条件得到满足, 所以我怎么能做到这一点?如何在windows phone中以编程方式制作按钮?
的按钮创建的XAML代码是
<Button x:Name="DeleteButton" Content="Delete" HorizontalAlignment="Left" Height="64" Margin="74,579,0,-9" VerticalAlignment="Top" Width="314" FontSize="24"/>
你有一个可见性属性。
你有一些方法可以做到这一点:
就在后面的代码,你应该:
if (condition)
{
DeleteButton.Visibility = Visibility.Visible; //Also possible to Collapse (hide).
}
上面的代码应该帮助你使按钮分别无形和有形。
注意:这是不太可取的,它不是动态的,可能会导致重复和不必要的代码。
更好的方式和更具活力的是:
你可以做一个布尔财产和能见度按钮绑定到它,就像这样:
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的资源,你应该添加的转换器,因此您可以用静态资源访问:
<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属性为您的需要,如果属实将势必可见,如果假的,它会崩溃。
if (condition)
{
IsVisible = true;
}
对于你应该了解更多信息:binding,converters。
你可以用XAML和结合做也:
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
</UserControl.Resources>
然后在控制使某事物喜欢:
在XAMLVisibility="{Binding IsVisible, Converter={StaticResource BooleanToVisibilityConverter}}"
和可见性是一个bool在ViewModel属性
+1但作为一个说明......这只适用于.NET 3.0及更高版本。 http://msdn.microsoft.com/en-us/library/system.windows.controls.booleantovisibilityconverter%28v=vs.110%29.aspx –
你不能只是gi将IsVisible属性设置为可见性数据类型而不是bool数据类型? –