2011-06-29 8 views
1

私は問題を説明するための簡単なプロジェクトを作成しました。依存関係プロパティを使用してユーザーコントロール内のコントロールを置き換えます。

<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> 

私は自分のアプリケーション全体でこのユーザーコントロールを使用したいが、私は真ん中のボタンを変更する必要があります。私は、ボタンや長方形を収容するユーザーコントロール(「ButtonPod」)を持っています。私はButtonのすべてのプロパティを制御する必要があるので、 'ButtonText'や 'ButtonSize'のようなDependencyPropertiesを公開したくないのです。コントロールを使用するたびにボタン全体を定義することになります。だから私はこのような依存関係プロパティ(「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'プロパティが設定されるが、ビジュアルツリーは更新されないことがわかります。何か案は?

答えて

1

名前付き要素を設定しても置き換えられません。親に名前を付けて、代わりにその子を追加したい(既存の子を置き換える)。

+0

右ボタンではなく、新しいボタンで(Buttonとしてのpod.ButtonOnPage = e.NewValue経由で)、Button = "ButtonOnPage" Margin = "50" Content = "Old button content" />ビジュアルツリーに影響を与えますか?プロパティはちょうど新しいボタンを設定する方法です..または私は思った。 –

+0

ありがとうございます - 問題は、x:Nameはページ上のものを参照するだけです。変更することはできません。基本的にはセットなしのgetのようです。助けてくれてありがとう。 –

+1

@Nick Bradley:生成されたデザイナーコードを見ると、名前付き要素ごとにメンバーがあることがわかります。これらはXamlに接続されていますが、依然としてプロパティです。名前付きプロパティを設定することによって、クラスメンバーを置き換えるだけで、それをビジュアルツリーに接続しません。私はこれらのプロパティがすべて '読み取り専用'とマークされるべきだと思う。 –

関連する問題