2010-07-28 77 views
2

我有自定義樣式的按鈕,我想將樣式項綁定到按鈕datacontext。 如何做到這一點?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;} 
} 
+0

你是否試圖綁定到資源名稱存儲在ContextText中的樣式?你能澄清你到底想做什麼嗎? – Stephan 2010-07-28 16:23:11

回答

4

嗯...這是你找什麼: -

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

我幾乎不好意思提交,它似乎是101.

0

這個e xample實際上工作時,我將代碼從按鈕點擊到方法到構造函數。

相關問題