【发布时间】:2011-06-29 18:10:39
【问题描述】:
我做了一个简单的项目来说明我的问题。我有一个包含一个按钮和一个矩形的用户控件('ButtonPod'):
<UserControl x:Class="SilverlightDependencyProp.ButtonPod"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<Rectangle Fill="Blue" />
<Button x:Name="ButtonOnPage" Margin="50" Content="Old button content" />
</Grid>
</UserControl>
我想在整个应用程序中使用此用户控件,但我需要更改中间的按钮。我需要控制 Button 的所有属性,所以我不想只公开像“ButtonText”或“ButtonSize”这样的 DependencyProperties - 我宁愿在使用控件时定义整个 Button。所以我像这样设置了一个依赖属性('CenterButton'):
public Button CenterButton
{
get { return (Button)GetValue(CenterButtonProperty); }
set { SetValue(CenterButtonProperty, value); }
}
public static readonly DependencyProperty CenterButtonProperty =
DependencyProperty.Register("CenterButton", typeof(Button),
typeof(ButtonPod), new PropertyMetadata(
CenterButtonChanged));
private static void CenterButtonChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var pod = d as ButtonPod;
pod.ButtonOnPage = e.NewValue as Button;
}
然后我尝试在我的 MainPage.xaml 上定义“CenterButton”,在我的用户控件中:
<Grid x:Name="LayoutRoot" Background="White">
<local:ButtonPod Width="200" Height="200">
<local:ButtonPod.CenterButton>
<Button Content="New button content" />
</local:ButtonPod.CenterButton>
</local:ButtonPod>
</Grid>
但是当我加载应用程序时,我看到的只是一个显示“旧按钮内容”的按钮——为什么我的按钮没有被替换?逐步进行,我可以看到 DependencyProperty 被命中并且 'ButtonOnPage' 属性被设置,但视觉树没有更新。有什么想法吗?
【问题讨论】:
标签: silverlight dependency-properties visual-tree