You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin绑定报错‘No data context found’,CountDisplay绑定失效求助

修复Xamarin绑定"No data context found"问题

方案1:在XAML中直接绑定自身作为BindingContext

核心问题是XAML解析时,你在代码中设置的BindingContext尚未生效,导致初始绑定失败。修改ContentPage标签,让XAML加载时直接关联当前页面作为数据源,无需在代码中手动设置:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="PapucoMetar.Views.Skener"
             BackgroundColor="White"
             BindingContext="{Binding RelativeSource={RelativeSource Self}}">
    <Grid RowDefinitions="*,Auto,Auto,*">
        <Label
                Grid.Row="1"
                FontSize="Large"
                HorizontalOptions="Center" 
                Text="{Binding CountDisplay}"/>
        <Button 
            x:Name="ButtonCount"
            Grid.Row="2"
            Text="Click me"
            Clicked="ButtonClicked_Clicked"
            />
    </Grid>
</ContentPage>

完成后可以删除构造函数中的BindingContext = this;代码,避免重复设置。

方案2:优化属性变更通知(可选但推荐)

修改CountDisplay属性的set方法,明确传递属性名称给OnPropertyChanged,让变更通知更精准,减少不必要的UI更新:

public string CountDisplay
{
    get => countDisplay;
    set
    {
        if (value == countDisplay)
            return;
        countDisplay = value;
        OnPropertyChanged(nameof(CountDisplay));
    }
}

额外检查点

  • 确认页面导航逻辑正确:确保通过Navigation.PushAsync(new Skener())或MainPage = new Skener()正确加载页面,避免实例化错误。
  • 排查是否有全局绑定设置、父页面代码覆盖了当前页面的BindingContext。

内容的提问来源于stack exchange,提问作者St3fKe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 21:23:14