【发布时间】:2012-05-29 19:13:05
【问题描述】:
我一直在使用 C# 在 Metro/XAML 中编写一个复杂的自定义控件。
为了说明我的观点,我创建了一个最小的场景供您参考。
一个简单的自定义控件如下:
public sealed class TestControl : Control
{
public static DependencyProperty TestTextProperty = DependencyProperty.Register("TestText", typeof(string), typeof(TestControl), new PropertyMetadata(string.Empty));
public string TestText
{
get { return (string) GetValue(TestTextProperty); }
set { SetValue(TestTextProperty, value); }
}
public static DependencyProperty TestColorProperty = DependencyProperty.Register("TestColor", typeof(Color), typeof(TestControl), new PropertyMetadata(Colors.Blue));
public Color TestColor
{
get { return (Color)GetValue(TestColorProperty); }
set { SetValue(TestColorProperty, value); }
}
public TestControl()
{
this.DefaultStyleKey = typeof(TestControl);
}
}
Thie 控件有两个依赖属性,一个 Text 属性和一个 color 属性。
这是我在 Generic.xaml 中的控件标准样式
<Style TargetType="local:TestControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:TestControl">
<Border
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<TextBlock Text="{TemplateBinding TestText}">
<TextBlock.Foreground>
<SolidColorBrush Color="{Binding Source={RelativeSource Mode=TemplatedParent}, Path=TestColor}" />
</TextBlock.Foreground>
</TextBlock>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
有两个问题:
1) 这段代码无法编译:
<Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
<local:TestControl x:Name="testcont" TestText="Hello" TestColor="Red" />
</Grid>
错误是:
XAML BlankPage.xaml 中的属性 TestColor 不允许使用值类型颜色
所以颜色的类型转换器似乎坏了(我假设)。 为了解决这个问题,我在代码隐藏中设置了 TestColor 属性:
public BlankPage()
{
this.InitializeComponent();
testcont.TestColor = Colors.Red;
}
这允许代码编译,但是颜色永远不会在模板中正确设置。我什至用了ValueConverter:
<TextBlock.Foreground>
<SolidColorBrush Color="{Binding Source={RelativeSource Mode=TemplatedParent}, Path=TestColor, Converter={StaticResource DebugConverter}}" />
</TextBlock.Foreground>
但是ValueConverter 中的断点从未被命中,这意味着绑定以某种方式静默失败。
似乎没有解决办法。有人可以解释一下这个问题吗?
谢谢
【问题讨论】:
-
您确定使用
System.UI.Color结构吗?如果是这样,那么您很可能在测试版中发现了一个错误(似乎已修复)。对此表示抱歉。
标签: c# silverlight xaml windows-runtime winrt-xaml