繁体   English   中英

自XAML以来,如何显示按钮?

[英]How can I show a button since 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时,它必须在用户控件中显示一个按钮,而当放置Decimal时,该按钮必须消失。 虽然,该属性也必须包含一个默认值。

我不知道是否必须在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}}"
/>

您可以通过元数据或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
  }
}

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

如果EntradaProperty除了通过属性Entrada以外没有任何其他更改,则此方法应该起作用:

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

默认值必须在其他位置指定,但是Entradas会启动,因为Entero sou显示开始处的按钮应该起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM