Reputation: 132
I have made a custom Button using expression blend and pasted it in my xaml code .
<phone:PhoneApplicationPage.Resources>
<Style x:Key="ButtonStyle1" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="Disabled"/>
<VisualState x:Name="MouseOver"/>
</VisualStateGroup>
<VisualStateGroup x:Name="FocusStates">
<VisualState x:Name="Focused"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Rectangle RadiusY="21" RadiusX="20" Stroke="White"/>
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</phone:PhoneApplicationPage.Resources>
I have then used this resource in my c# code to change color, font size, background , foreground and all properties dynamically possible.
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
createButton();
}
public void createButton()
{
Button buttton = new Button { Height = 100, Background = new SolidColorBrush(Colors.Blue), Width = 300, Content = " Button", Style = this.Resources["ButtonStyle1"] as Style };
ContentPanel.Children.Add(buttton);
}
But i am unable to do so , no change is being reflected in button. Is there any way . I know that i have to change color of rectangle . But do not know how to do it . I tried a lot. Thanks.
Upvotes: 1
Views: 1637
Reputation: 7112
Well, what properties should affect which? You created a custom control template for your button which means you decide how it is drawn. If you take a look at your template, your button consists of a Grid
with two child controls: a Rectangle
and a ContentPresenter
.
Now, when you say:
var btn = new Button
{
Background = new SolidColorBrush(Color.Blue);
};
What should become blue? The Grid
? The Rectangle
control? ContentPresenter
? This question is not answerable in principle and you need to decide which control in the ControlTemplate
inherits parent's properties.
To put it in another words: Button
's properties are transferred down to the controls in the ControlTemplate
via TemplateBinding
. So if you wanted to transfer the meaning of Button.Background
to Rectangle.Background
, you would change the template to this:
<Rectangle RadiusY="21" RadiusX="20" Stroke="White"
Fill="{TemplateBinding Background}"/>
And now you get something that might be what you wanted. When you set Button.Background
you merely transfer it to the target subcontrol since there is no Button
in the visual tree, it is replaced by it's control template.
Upvotes: 2