views:

196

answers:

1

I'm having some trouble styling a custom control that I built. Here's the control source:

namespace SilverlightStyleTest
{
    public class AnotherControl: TextBox
    {
        public string MyProperty { get; set; }
    }
}

In the same namespace & project I try to create a style with a setter for MyProperty like so:

<UserControl x:Class="SilverlightStyleTest.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Local="clr-namespace:SilverlightStyleTest">

    <UserControl.Resources>
        <Style x:Name="AnotherStyle" TargetType="Local:AnotherControl">
            <Setter Property="Width" Value="200"/>
            <Setter Property="MyProperty" Value="Hello."/>
        </Style>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot">
        <Local:AnotherControl Style="{StaticResource AnotherStyle}"/>
    </Grid>
</UserControl>

I end up with the runtime error: Invalid attribute value MyProperty for property Property. [Line: 9 Position: 30]

I can't figure out what's wrong with the style to cause this error. I also tried "fully qualifying" the property name as "Local:AnotherControl.MyProperty" but that didn't work either.

+2  A: 

Non-dependency properties cannot be set in styles.

You need to define it as a DependencyProperty:

public static readonly DependencyProperty MyPropertyProperty =
    DependencyProperty.Register("MyProperty", typeof(string), typeof(AnotherTextBox),
        new FrameworkPropertyMetadata((string)null));

public string MyProperty
{
    get { return (string)GetValue(MyPropertyProperty); }
    set { SetValue(MyPropertyProperty, value); }
}
kek444
Beat me by seconds!
Will Eddins
Man that was quick! Double points for speed? ;)
James Cadd
Experience and open VS, my dear Watson ;)
kek444