如何重用相同的Watermark TextBox

时间:2013-07-24 14:36:15

标签: wpf xaml dependency-properties

我有一个继承TextBox的WatermarkTextBox,我有x:Name =“TestASearch”,它将在listview中调用以显示 从textboxsearch_TextChanged方法返回的搜索。

        <controls:WatermarkTextBox x:Name="TestASearch"  Grid.Column="2" Grid.Row="0"
                Margin="10,61,0,10" SelectAllOnGotFocus="True"  Background="White"
                TextChanged="textboxsearch_TextChanged">
                <controls:WatermarkTextBox.Watermark>
                    <TextBlock  FontStyle="Italic"   Text="Enter search text…" Width="116"/>
                </controls:WatermarkTextBox.Watermark>

WatermarkTextBox类

    public WatermarkTextBox()
    {
        FrameworkElement.DefaultStyleKeyProperty.OverrideMetadata(typeof(WatermarkTextBox), new FrameworkPropertyMetadata(typeof(WatermarkTextBox)));
    }

现在我想使用相同的概念,除了我想要一个不同的x:Name = TestBSearch并想使用TextChanged =“textboxsearch_TextChanged”

            <controls:WatermarkTextBox x:Name="TestBSearch"  Grid.Column="2" Grid.Row="0"
                Margin="10,61,0,10" SelectAllOnGotFocus="True"  Background="White"
                TextChanged="textboxsearch_TextChanged">
                <controls:WatermarkTextBox.Watermark>
                    <TextBlock  FontStyle="Italic"   Text="Enter search text…" Width="116"/>
                </controls:WatermarkTextBox.Watermark>
            </controls:WatermarkTextBox>

当我尝试这个时,我收到错误“PropertyMetadata已经注册了'WatermarkTextBox'类型。”如何重用相同的代码?

由于

1 个答案:

答案 0 :(得分:1)

DefaultStyleKeyProperty.OverrideMetadata应该在静态构造函数中设置:

static WatermarkTextBox()
{
    FrameworkElement.DefaultStyleKeyProperty.OverrideMetadata(typeof(WatermarkTextBox), new FrameworkPropertyMetadata(typeof(WatermarkTextBox)));
}