代码之家  ›  专栏  ›  技术社区  ›  veljkoz Danko Valkov

WPF文本框:设置样式时出错

  •  1
  • veljkoz Danko Valkov  · 技术社区  · 14 年前

    我已经为文本框定义了样式,当文本框为空时,该样式将显示关于输入内容的提示。

    这将是我的窗口:

    <Grid>
        <Grid.Resources>
            <Style TargetType="{x:Type TextBox}" x:Key="stlHintbox">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Text, RelativeSource={RelativeSource Mode=Self}}" Value="">
                        <Setter Property="Background">
                            <Setter.Value>
                                <VisualBrush Stretch="None">
                                    <VisualBrush.Visual>
                                        <TextBlock Text="First name" FontStyle="Italic" Foreground="LightGray" />
                                    </VisualBrush.Visual>
                                </VisualBrush>
                            </Setter.Value>
                        </Setter>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Grid.Resources>
        <TextBox Style="stlHintbox" />
    </Grid>
    

    抛出的错误是:

    'Set property 'System.Windows.FrameworkElement.Style' threw an exception.' Line number '22' and line position '11'.

    内部除外:

    "'stlHintbox' is not a valid value for property 'Style'."

    样式放置在内部时正常工作 <TextBox.Style> ,那我做错什么了?

    1 回复  |  直到 14 年前
        1
  •  6
  •   Jay    14 年前
    Style="{StaticResource stlHintbox}"
    

    您需要使用标记扩展语法从字典中引用资源。

    如果资源在范围内并且在设计时可用,则可以使用 StaticResource DynamicResource 缺点是完全缺乏编译器检查。