私は自分の問題を説明するために簡単なプロジェクトを作成しました。ボタンと長方形を格納するユーザーコントロール(「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」プロパティが設定されていることがわかりますが、ビジュアルツリーは更新されません。何か案は?