在某些情况下(使用TranslateTransform时),TemplateBinding无法正常工作。

7
这是我在WPF中重现此问题的方法:
创建一个自定义控件:
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));
}

在Generic.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>

运行应用程序后,发现“文本”正常工作,但“偏移量”无法正常工作。我在Windows Phone 7开发环境中尝试了类似的事情,并得到了相同的结果。

我应该如何修改代码以使偏移量正常工作?

谢谢。


根据《WPF 4.5 Unleashed》(第三版,作者:Nathan, Adam;出版年份:2014年),第437页的描述,您不能在Freezeable的属性上使用TemplateBindingTranslateTransform是一个Freezeable,这就是为什么它不起作用的原因(而TextBlock不是Freezeable,所以它在那里起作用)。令人困惑的是,这不是运行时(或任何其他时间)错误。它只是默默地失败了。 - Stevens Miller
2个回答

21

尝试:

{Binding Offset, RelativeSource={RelativeSource TemplatedParent}}

刚刚再次测试,它不适用于Silverlight3,但适用于Silverlight4。 - Cui Pengfei 崔鹏飞
1
WP7.0的“Silverlight 4”相对较为稀缺。随着WP7.1(又名Mango)一起发布的Silverlight4实现更加完整,崔鹏飞的解决方案可能会开始运作。 - Peter Wone
1
我现在正在运行Mango和Kent的解决方案(完整的相对源语法),在Mango下确实可以工作。这很好,因为现在TemplateBinding语法在框架内产生了“未指定的异常”。如果可以的话,我建议还包括Mode=OneWay,因为这使其在语义上与TemplateBinding完全相同,更加高效。 - Peter Wone
我在使用TemplateBinding时遇到了问题。将其更改为长格式帮助我找出了问题所在。谢谢! - Ashley Grenon
4
希望我能理解那种魔法。 - Tiago Almeida

1

如果你的目标是WP7.0(Silverlight 3),那么TemplateBing和RelativeSource都不起作用,所以最好忘记它们。 可以使用其他方法来解决问题。 实际上,每次“OffSet”更改时,我都会手动更改每个变换的X/Y值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接