C# 按钮文本模板数据绑定不工作

C# 按钮文本模板数据绑定不工作,c#,xaml,data-binding,windows-8,C#,Xaml,Data Binding,Windows 8,我正在开发我的第一个Windows 8应用程序,在一个页面中,我试图在页面加载时用最新的timestop更新按钮文本。我定义了我的xaml和codebehind,如下所示: 我正在使用数据绑定更新按钮文本,但未按预期工作: MainPage.xaml <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> <Button HorizontalAlignment="Left" Mar

我正在开发我的第一个Windows 8应用程序,在一个页面中,我试图在页面加载时用最新的timestop更新按钮文本。我定义了我的xaml和codebehind,如下所示:

我正在使用数据绑定更新按钮文本,但未按预期工作:

MainPage.xaml

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <Button HorizontalAlignment="Left" Margin="333,284,0,0" VerticalAlignment="Top" Height="69" Width="162">
        <Button.Resources>
            <DataTemplate x:Key="DataTemplate1">
                <Grid>
                    <TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding ButtonText}"  VerticalAlignment="Top" Foreground="#FFFF6800" Height="34" Margin="-30,0,-22,-14" Width="115"/>
                </Grid>
            </DataTemplate>
        </Button.Resources>
        <Button.ContentTemplate>
            <StaticResource ResourceKey="DataTemplate1"/>
        </Button.ContentTemplate>
    </Button>

</Grid>
statclass.cs

public StatsClass Stats { get; private set; }

    public MainPage()
    {
        this.InitializeComponent();
        this.DataContext = Stats;
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        UpdateButton();
    }

    private void UpdateButton()
    {
        if (Stats == null)
            Stats = new StatsClass();

        Stats.ButtonText = DateTime.Now.ToString();
    }
public class StatsClass : INotifyPropertyChanged
{
    private string _buttonText;
    public string ButtonText
    {
        get
        {
            return _buttonText;
        }

        set
        {
            _buttonText = value;
            OnPropertyChanged("ButtonText");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
}

您已经设置了两次按钮的内容,一次是使用
Content=“Button”
,另一次是使用。
Button.ContentTemplate
。你可以:

<Button HorizontalAlignment="Left" Margin="333,284,0,0" VerticalAlignment="Top" Height="69" Width="162">
    <Grid>
         <TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding ButtonText}"  VerticalAlignment="Top" Foreground="#FFFF6800" Height="34" Margin="-30,0,-22,-14" Width="115"/>
    </Grid>
</Button>

我昨天在数据模板中使用绑定时遇到了类似的问题。我猜您在调试输出中也有绑定错误。 我用这样一个相对的来源解决了这个问题:

<TextBlock Text={Binding DataContext.ButtonText, 
           RelativeSource={RelativeSource FindAncestor, AncestorType=*YourControl*}}"/>

我想您将不得不在主页中调用已更改的属性also@SandeepChauhan不,你不会担心这是问题中的一个输入错误,我更改了它-但它没有触发绑定。你是否在属性设置器中设置了断点以验证它是否被设置,您是否监视了绑定错误的调试输出?感谢提供有关绑定错误的提示。事实上,它有一个错误-修复程序是在绑定定义中添加ElementName。好的,我想这是因为您使用的是模板,您不需要使用其他方式,例如在上面的代码中,将DataContext设置为inherited,并将其设置为
StatClass