按钮文本模板数据绑定不起作用

时间:2013-12-11 06:56:58

标签: c# xaml data-binding windows-8

我正在开发我的第一个Windows 8应用程序,在一个页面中我尝试在页面加载时使用最新的时间戳更新按钮文本。我在下面定义了我的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>

MainPage.xaml.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();
    }

StatsClass.cs

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

2 个答案:

答案 0 :(得分:1)

您已将按钮的内容设置两次,一次使用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>

答案 1 :(得分:0)

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

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

模板无法直接访问datacontext。通过使用相对源,您可以绑定到其属性。