0

我创建了一个 WPF UserCotrol。在它里面我有 3 个默认的网格
visibility="collapsed"。我创建了一个这样的依赖属性:

public int PanelId
    {
        get { return (int)GetValue(PanelIdProperty); }
        set { SetValue(PanelIdProperty, value); }
    }

public static readonly DependencyProperty PanelIdProperty =
        DependencyProperty.Register("PanelId", typeof(int), typeof(RecurrencePattern), new UIPropertyMetadata(1));

我想在另一个 xaml 中使用这个用户控件。我这样声明:

<uc:RecurrencePattern PanelId="2"/>

我认为通过这样做,PanelId 将为 2,并且在运行时的默认构造函数中,我可以使用它来设置可见的面板。相反,PanelId 是 UIPropertyMetadata(1) 定义的 1。如何使用 xaml 中提供的值来设置哪个网格可见。我有:

<Grid x:Name="a" Visibility="Collapsed">
    <label Content"a"/>  
</Grid>
<Grid x:Name="b" Visibility="Collapsed">
    <label Content"b"/>  
</Grid>
<Grid x:Name="c" Visibility="Collapsed">
    <label Content"c"/>  
</Grid>

在默认构造函数中是这样的:

switch (PanelId)
  {
    case 1:
      a.Visibility = System.Windows.Visibility.Visible;
      break;
    case 2:
      b.Visibility = System.Windows.Visibility.Visible;
      break;
    case 3:
      c.Visibility = System.Windows.Visibility.Visible;
      break;
    default:
      a.Visibility = System.Windows.Visibility.Visible;
      break;
}

谢谢你。

4

1 回答 1

1

更改代码Visibility需要在依赖属性更改事件中......

  public static readonly DependencyProperty PanelIdProperty
     = DependencyProperty.Register(
          "PanelId",
          typeof(int),
          typeof(RecurrencePattern),
          new UIPropertyMetadata(1, PanelIdPropertyChangedCallback)); 

    private static void PanelIdPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var recurrencePattern = d as RecurrencePattern;
        if (recurrencePattern != null)
        {
            var panelId = Convert.ToInt32(e.NewValue);
            switch (panelId)
            {
                case 1:
                    recurrencePattern.Visibility
                       = System.Windows.Visibility.Visible;
                    break;
                case 2:
                    recurrencePattern.Visibility
                       = System.Windows.Visibility.Visible;
                    break;
                case 3:
                    recurrencePattern.Visibility 
                       = System.Windows.Visibility.Visible;
                    break;
                default:
                    recurrencePattern.Visibility 
                       = System.Windows.Visibility.Visible;
                    break;
            }
        }
    }

希望这可以帮助...

于 2012-05-16T09:25:39.050 回答