WP7 - 将类绑定到网格

时间:2012-11-20 22:25:04

标签: c# windows-phone-7 xaml data-binding

我有这样的网格:

<Grid x:Name="LayoutRoot" Background="Transparent" DataContext="{Binding}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <TextBlock x:Name="CurrentPoints" Grid.Row="1" Grid.Column="0" 
            Text="{Binding CurrentPoints}" Width="100" Height="100" Foreground="Red">
    </TextBlock>
    <TextBlock x:Name="PointsLeft" Grid.Row="1" Grid.Column="1" 
        Text="{Binding AllPoints}" Width="100" Height="100" Foreground="Red" />
    <TextBlock x:Name="AllPoints" Grid.Row="1" Grid.Column="2" 
        Text="{Binding EndPoints}" Grid.ColumnSpan="1"/>
     </Grid>

这样的页面代码:

Counter pocitadlo = new Counter(200);

        public MainPage()
        {
            InitializeComponent();
            Loaded += MainPage_Loaded;

        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            LayoutRoot.DataContext = pocitadlo;
        }

这是我的反击班:

class Counter : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private int _currentPoints;
    public int CurrentPoints
    {
        get
        {
            return _currentPoints;
        }
        set
        {
            this._currentPoints = value;
            onPropertyChanged(this, "CurrentPoints");
        }
    }
    private int _allPoints;
    public int AllPoints
    {
        get
        {
            return _allPoints;
        }
        set
        {
            this._allPoints = value;
            onPropertyChanged(this, "AllPoints");
        }
    }
    private int _endPoints;
    public int EndPoints
    {
        get
        {
            return _endPoints;
        }
        set
        {
            this._endPoints = value;
            onPropertyChanged(this, "EndPoints");
        }
    }

    public Counter(int endPoints)
    {
        this._allPoints = 0;
        this._currentPoints = 0;
        this._endPoints = endPoints;
    }

    private void onPropertyChanged(object sender, string property)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(sender, new PropertyChangedEventArgs(property));

        }
    }
}

为什么绑定工作?我错过了什么?感谢

0 个答案:

没有答案