我创建了一个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并且在默认构造函数中运行时我可以使用它来设置哪些面板可见。 而是由UIPropertyMetadata(1)定义的PanelId为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;
}
谢谢。
答案 0 :(得分: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;
}
}
}
希望这会有所帮助......