自XAML以来,我怎样才能显示一个按钮?

问题描述:

让我给你提供更多的细节。情况是我正在处理一个用户控件,并且我有一个依赖对象接收一个枚举。根据值,必须显示一个按钮。自XAML以来,我怎样才能显示一个按钮?

我的意思是:

public enum Entradas 
{ 
    Entero, Decimal 
} 

public partial class TableroUserControl : UserControl 
{ 
    public Entradas Entrada 
    { 
     get { return (Entradas)GetValue(EntradaProperty); } 
     set { SetValue(EntradaProperty, value); } 
    } 

    public static readonly DependencyProperty EntradaProperty = 
     DependencyProperty.Register("Entrada", typeof(Entradas), typeof(TableroUserControl)); 
} 

当EntradaProperty接收Entradas.Entero,它必须显示在用户的控制按钮,并把小数时,必须消失的按钮。虽然,该属性也必须包含默认值。

我不知道是否必须在EntradaProperty中声明PropertyMetadata对象或使用IValueConverter。

我该怎么做?提前致谢。

您可以创建一个IValueConverter实现来执行您所需的操作。结果将是一个System.Windows.Visibility对象;

class EntradasToVisibilityConverter : IValueConverter 
{ 
    public Object Convert(
    Object value, 
    Type targetType, 
    Object parameter, 
    CultureInfo culture) 
    { 
     // error checking, make sure 'value' is of type 
     // Entradas, make sure 'targetType' is of type 'Visibility', etc. 

     return (((Entradas)value) == Entradas.Entero) 
       ? Visibility.Visible 
       : Visibility.Collapsed; 
    } 

    public object ConvertBack(
    object value, 
    Type targetType, 
    object parameter, 
    CultureInfo culture) 
    { 
     // you probably don't need a conversion from Visibility 
     // to Entradas, but if you do do it here 
     return null; 
    } 
} 

现在,在XAML ...

<SomeParentControl.Resources> 
    <myxmlns:EntradasToVisibilityConverter x:key="MyEntradasToVisConverter" /> 
</SomeParentControl.Resources> 
<Button 
    Visibility="{Binding MyEnumValue, Converter={StaticResource MyEntradasToVisConverter}}" 
/> 

您可以在TableroUserControl的XAML中使用自定义IValueConverter或声明DataTrigger

您可以通过元数据或由ValueConverter做到这一点。已经给出了valueConverter的示例。这里是一个通过元数据来做的例子。

public static readonly DependencyProperty EntradaProperty = 
     DependencyProperty.Register("Entrada", typeof(Entradas), typeof(TableroUserControl), new UIPropertyMetadata((d,e)=> { ((TableroUserControl)d).EntradaPropertyChanged(e); })); 

private EntradaPropertyChanged(DependencyPropertyChangedEventArgs e){ 
    Entradas entrada=(Entradas)e.NewValue ; 
    if(entrada=Entradas.Entero) 
    // Show your control 
    }else{ 
    // Hide your control 
    } 
} 

如果EntradaProperty不以任何其他方式通过属性Entrada变化比这应该工作:

public Entradas Entrada 
{ 
    get { return (Entradas)GetValue(EntradaProperty); } 
    set 
    { 
     SetValue(EntradaProperty, value); 
     if (Entrada == Entradas.Entero) 
      //show button 
     else 
      //hide button 
    } 
} 

默认值就必须另行规定,但入住日期将开始为肠嗖展示在开始的按钮应该工作。