如何在XAML中为Universal Apps创建“可设置”的自定义控件?

时间:2014-08-08 07:12:54

标签: custom-controls winrt-xaml win-universal-app

我创建了一个自定义控件:

internal sealed class FieldControl : Control
{
    public FieldControl()
    {
        this.DefaultStyleKey = typeof (FieldControl);
    }

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

    public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(FieldControl), new PropertyMetadata(null));
}

具有以下样式:

<Style TargetType="localControls:FieldControl">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="localControls:FieldControl">
                <Grid Width="{TemplateBinding Width}" Height="{TemplateBinding Height}">
                    <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding Foreground}" BorderThickness="1"></Border>
                    <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{TemplateBinding Text}" Foreground="{TemplateBinding Foreground}" FontSize="24"></TextBlock>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

并使用它:

<localControls:FieldControl Width="70" Height="70" Text="{Binding}" Background="DarkSlateBlue" Foreground="Cyan"></localControls:FieldControl>

现在,这看起来没问题,直到我在运行时添加更多属性来设置和更改。因此,我想将一种风格应用于FieldControl。所以,除了上述内容,我应该能够做到:

<localControls:FieldControl Width="70" Height="70" Text="{Binding}" Style="{StaticResource State1Style}"></localControls:FieldControl>

State1Style的位置:

<Style x:Key="State1Style" TargetType="localControls:FieldControl">
    <Setter Property="Background" Value="DarkSlateBlue"></Setter>
    <Setter Property="Foreground" Value="Cyan"></Setter>
</Style>

然而,由于某种原因,这并没有奏效。首先,Visual Studio(安装了ReSharper)抱怨找不到State1Style。其次,当我运行应用程序FieldControl时根本没有应用任何样式...基本上我在屏幕上看不到任何内容。

我在网上搜索,没有找到关于这个主题的文章。如果有人能帮我解决这个问题,我感激不尽。

最终目标是让StyleSelector根据控件状态在运行时选择样式。

1 个答案:

答案 0 :(得分:0)

我有幸在样式中覆盖了模板。

<Style x:Key="State1Style" TargetType="localControls:FieldControl">
    <Setter Property="Background" Value="DarkSlateBlue"></Setter>
    <Setter Property="Foreground" Value="Cyan"></Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="localControls:FieldControl">
                <Grid Width="{TemplateBinding Width}" Height="{TemplateBinding Height}">
                    <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding Foreground}" BorderThickness="1"></Border>
                    <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{TemplateBinding Text}" Foreground="{TemplateBinding Foreground}" FontSize="24"></TextBlock>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>