2011-06-14 9 views
7

これは、私はWPFでこの問題を再現する方法である:TemplateBindingのは、特定のケースでは動作しません

は、カスタムコントロールを作成します。

public class TestCustomControl : Control 
{ 
static TestCustomControl() 
{ 
    DefaultStyleKeyProperty.OverrideMetadata(typeof(TestCustomControl), new FrameworkPropertyMetadata(typeof(TestCustomControl))); 
} 

public string Text 
{ 
    get { return (string)GetValue(TextProperty); } 
    set { SetValue(TextProperty, value); } 
} 

// Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc... 
public static readonly DependencyProperty TextProperty = 
    DependencyProperty.Register("Text", typeof(string), typeof(TestCustomControl), new PropertyMetadata("Hello")); 

public double OffSet 
{ 
    get { return (double)GetValue(OffSetProperty); } 
    set { SetValue(OffSetProperty, value); } 
} 

// Using a DependencyProperty as the backing store for OffSet. This enables animation, styling, binding, etc... 
public static readonly DependencyProperty OffSetProperty = 
    DependencyProperty.Register("OffSet", typeof(double), typeof(TestCustomControl), new PropertyMetadata(5.0)); 
} 

は一般に、それのスタイルを追加します。 XAMLファイル:

<Style TargetType="local:TestCustomControl"> 
<Setter Property="Template"> 
    <Setter.Value> 
     <ControlTemplate TargetType="local:TestCustomControl"> 
      <Grid> 
       <TextBlock Text="{TemplateBinding Text}"></TextBlock> 
       <TextBlock Text="{TemplateBinding Text}"> 
        <TextBlock.RenderTransform> 
         <TranslateTransform X="{TemplateBinding OffSet}" Y="{TemplateBinding OffSet}"/> 
         <!--<TranslateTransform X="10" Y="10"/>--> 
        </TextBlock.RenderTransform> 
       </TextBlock> 
      </Grid> 
     </ControlTemplate> 
    </Setter.Value> 
</Setter> 

そして、メインウィンドウに追加:

<local:TestCustomControl OffSet="32" Text="the off set is not working" FontSize="36"> 

    </local:TestCustomControl> 

アプリケーションを実行すると、「テキスト」が正しく動作することがわかりましたが、「OffSet」は機能しません。 Windows Phone 7開発環境でも同様のことを試みましたが、同じ結果が得られました。

OffSetを動作させるためにコードを変更する方法を教えてください。

おかげ

+0

"WPF 4.5 Unleashed、" Nathan、Adam;第3版c。 2014年、p。 437、 'Freezeable'のプロパティで' TemplateBinding'を使うことはできません。 'TranslateTransform'は' Freezeable'なので、なぜ動作しませんでした( 'TextBlock'は' Freezeable'ではないので、そこで動作しました)。困惑しているのは、これが実行時(またはいつでも)のエラーではないということです。それはちょうど偶然に失敗します。 –

答えて

17

試してみてください。

{Binding Offset, RelativeSource={RelativeSource TemplatedParent}} 
+0

wpfではWP7ではなく、 – CuiPengFei

+0

が再びテストされ、Silverlight3では動作しません。Silverlight4で動作します。 – CuiPengFei

+1

WP7.0にはかなり薄い「Silverlight 4」があります。 WP7.1(Mangoとも呼ばれる)に同梱されているSilverlight4の実装ははるかに完全であり、CuiPengFeiのソリューションはおそらく動作し始めます。 –

1

TemplateBingとRelativeSourceの両方が動作するので、あなたはWP7.0(Silverlightの3)をターゲットにしている場合は、単にそれを忘れないでください。 他の方法でそれを回避してください。 "OffSet"が変更されるたびに、実際には各トランスフォームのX/Y値を手動で変更しました。

関連する問題