Ievgen
Ievgen

Reputation: 4443

Silverlight. Bind style items to the datacontext

I have a button with a custom style and I would like to style items to the button datacontext. Any idea what is wrong with the code below?

This is what I have done:

   <UserControl.Resources>
  <Style x:Key="ButtonStyle1" TargetType="Button">
   <Setter Property="Template">
    <Setter.Value>
     <ControlTemplate TargetType="Button">
      <Grid>
       <TextBlock TextWrapping="Wrap" Text="{Binding ContextText}" DataContext="{TemplateBinding DataContext}"/>
      </Grid>
     </ControlTemplate>
    </Setter.Value>
   </Setter>
  </Style>
 </UserControl.Resources>

    <Grid x:Name="LayoutRoot" Background="White">
     <Button Content="Button" Height="131" Width="103" HorizontalAlignment="Left" VerticalAlignment="Top" Click="Button_Click"/>
     <Button x:Name="button" Style="{StaticResource ButtonStyle1}" Margin="165,86,0,0"/>

    </Grid>

C# code

 public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
    {
  button.DataContext=new Test(){ ContextText="TextFromContext"};
button.UpdateLayout();
    }
}
 public class Test
 {
  public String ContextText{get;set;}
 }

Upvotes: 2

Views: 705

Answers (1)

AnthonyWJones
AnthonyWJones

Reputation: 189535

Umm.. is this what you looking for:-

<Button x:Name="button" Content="{Binding ContextText}" Style="{StaticResource ButtonStyle1}" Margin="165,86,0,0"/> 

I'm almost embarrassed to submit it, it seem so 101.

Upvotes: 3

Related Questions