WPF - DataBind TextBlock.Text到Integer

时间:2010-11-29 21:13:28

标签: wpf data-binding integer textblock

我知道这是一个非常简单的问题..

我有一个Textblock谁的文本属性我想要数据绑定到我在代码隐藏中的整数..现在我正在这样做

<TextBlock Name="TextBlockCompeltedSongsNumber" Text="{Binding}"></TextBlock>

然后在c#..

            this.TextBlockCompeltedSongsNumber.DataContext = CompeltedTracks;

CompletedTracks是public int

我错过了什么?

2 个答案:

答案 0 :(得分:1)

最后我创建了一个实现了INotifyPorpertyChange

的类
    //Global Declaration
information info = new information();

...后

            this.TextBlockCompeltedSongsNumber.DataContext = info;

和信息类

public class information : INotifyPropertyChanged
{
    private int failedTracks = 0;
    public int FailedTracks { get { return failedTracks; } set { failedTracks = value; OnPropertyChanged("FailedTracks"); } }
    private int compeltedTracks = 0;
    public int CompeltedTracks { get { return compeltedTracks; } set { compeltedTracks = value; OnPropertyChanged("CompeltedTracks"); } }

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

最后在xaml

                    <TextBlock Name="TextBlockCompletedSongs" Margin="5,0,5,0">Completed Songs:</TextBlock>
                <TextBlock Name="TextBlockCompeltedSongsNumber" Text="{Binding Path=CompeltedTracks}"></TextBlock>
                <TextBlock Name="TextBlockFailedSongs" Margin="5,0,5,0">Failed Songs:</TextBlock>
                <TextBlock Name="TextBlockFailedSongsNumber" Text="{Binding Path=FailedTracks}"></TextBlock>

对于一些应该简单的事情来说似乎做了很多工作......但是我不能让它以任何其他方式工作......我不知道我做错了什么:O

答案 1 :(得分:0)

也许你设置DataContext太晚了。渲染之后。

直接绑定到属性并引发PropertyChanged事件会不会更好?

<TextBlock Text="{Binding CompletedTracks}"></TextBlock>

并将TextBlock父级的DataContext设置为CompletedTracks的所有者。