I'm trying to setup a TextBox subclass that will change its style based on a few different things, and I'm running into two problems. The first Trigger, the VisualBrush one, triggers properly but won't write the text in the String myName. I tried making myName a property but for some reason the set method throws a StackOverFlowException.
The second problem is with the DataTrigger, which isn't getting triggered even though isRequired is set to false.
This is all within a custom control that inherits TextBox.
Here's my XAML:
<TextBox.Style>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Text" Value="">
<Setter Property="Background">
<Setter.Value>
<VisualBrush Stretch="None">
<VisualBrush.Visual>
<TextBlock Foreground="Gray" FontSize="24">
<TextBlock.Text>
<Binding Path="myName" RelativeSource="{RelativeSource Self}" />
</TextBlock.Text>
</TextBlock>
</VisualBrush.Visual>
</VisualBrush>
</Setter.Value>
</Setter>
</Trigger>
<DataTrigger Binding="{Binding Path=isRequired, Source={RelativeSource Self}}" Value="False">
<Setter Property="Text" Value="100" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
CS:
public partial class SuperTB : TextBox
{
public String myName
{
get { return myName; }
set {}
}
DependencyProperty isRequiredProperty = DependencyProperty.Register("isRequired", typeof(Boolean), typeof(SuperTB));
public Boolean isRequired
{
get { return (Boolean)GetValue(isRequiredProperty); }
set { SetValue(isRequiredProperty, value); }
}
public SuperTB()
{
InitializeComponent();
myName = "Unicorns!";
}
}
This is the code that StackOverflows it. Also failing to work but no Exception is:
public string myName = "Rainbows!";
public string myName
{
get { return myName; }
set {}
}
that property getter is returning itself, hence the stack overflow.
and the setter is doing nothing, hence the "failing to work"
you probably want:
private string myName; // lower case!
public string MyName // upper case!
{
get { return myName; }
set { myName = value; }
}
or even
public string myName { get; set; }
and even then this still won't work like you expect, since nothing is firing any property change notifications there, so nobody will notice that myName ever changes.