TemplateBinding does not work in certain cases(when using TranslateTransform)

荒凉一梦 提交于 2019-12-13 12:05:48

问题


This is how I reproduced this problem in WPF:

Create a custom control:

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));
}

Add a style for it in the Generic.xaml file:

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

Then add it to the main window:

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

    </local:TestCustomControl>

Then run the application, it turned out the "Text" works fine but the "OffSet" does not work. And I tried the similar thing in Windows Phone 7 development environment, and I got the same result.

How should I modify the code to make the OffSet work?

Thanks


回答1:


Try:

{Binding Offset, RelativeSource={RelativeSource TemplatedParent}}



回答2:


Both of TemplateBing and RelativeSource do not work, so just forget about it if you are targeting WP7.0 (Silverlight 3). Use some other ways to work it around. I actually manually changed the X/Y values of each transform every time the "OffSet" is changed.



来源:https://stackoverflow.com/questions/6346594/templatebinding-does-not-work-in-certain-caseswhen-using-translatetransform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!