Silverlight的。将样式项绑定到datacontext

时间:2010-07-28 09:27:24

标签: c# .net wpf silverlight

我有自定义样式的按钮,我想将样式项绑定到按钮datacontext。 怎么做?

我的尝试:

   <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#代码

 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;}
 }

2 个答案:

答案 0 :(得分:4)

嗯..这就是你要找的东西: -

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

我几乎不好意思提交它,它似乎是101。

答案 1 :(得分:0)

当我将代码从按钮单击移动到方法到构造函数时,此示例实际工作。