TemplateBinding не работает в некоторых случаях (при использовании TranslateTransform)
Вот как я воспроизвел эту проблему в 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>
Затем запустите приложение, оказалось, что "Текст" работает нормально, но "OffSet" не работает. И я попробовал то же самое в среде разработки Windows Phone 7, и я получил тот же результат.
Как мне изменить код, чтобы заставить работать OffSet?
Спасибо
2 ответа
Решение
Пытаться:
{Binding Offset, RelativeSource={RelativeSource TemplatedParent}}
Оба TemplateBing и RelativeSource не работают, поэтому просто забудьте об этом, если вы ориентируетесь на WP7.0 (Silverlight 3). Используйте некоторые другие способы обойти это. Я фактически вручную изменял значения X/Y каждого преобразования каждый раз, когда изменяется "OffSet".