c# - 当前上下文中不存在 Xamarin C# 按钮引用
问题描述
我使用 Xamarin 开发应用程序
基本上管理员用户应该能够访问此按钮。我以前使用过这个逻辑并且效果很好。
普通用户不应有权隐藏其他普通用户的评论。
有人告诉我,它嵌套在轮播视图中存在问题。
我可以重组整个事情,但我喜欢目前使用的设计
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="GOV.ReviewPage" Title="Reviews" >
<Grid RowDefinitions="20,180,20,32,230,90" ColumnDefinitions="20,*,20">
<Frame Grid.Row="1" Grid.Column="1" Grid.RowSpan="2">
<CarouselView x:Name="MainCarousel" IndicatorView="indicatorView" IsBounceEnabled="True" >
<CarouselView.ItemTemplate>
<DataTemplate>
<ScrollView>
<Grid RowDefinitions="20,20,*" ColumnDefinitions="75,*" Margin="15,0,25,0">
<Label Text="Username:" Grid.Row="0" Grid.Column="0" HorizontalTextAlignment="Start" />
<Label Text="{Binding User.Username}" FontSize="15" Grid.Row="0" Grid.Column="1" HorizontalTextAlignment="Start" />
<Label Text="Description:" Grid.Row="1" Grid.Column="0" HorizontalTextAlignment="Start" />
<Label Text="{Binding Description}" FontSize="15" HorizontalTextAlignment="Start" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2"/>
<Frame Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" >
<Button x:Name="HideButtonRef" Clicked="HideButton" Text="{Binding stringVal}"
HeightRequest="50" />
</Frame>
</Grid>
</ScrollView>
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
</Frame>
</Grid>
</ContentPage>
和有问题的 C# 逻辑:
protected override async void OnAppearing()
{
if (User.Admin) { HideButtonRef.IsEnabled = false; } // this doesnt work for some reason
else {HideButtonRef.IsEnabled = true; }
base.OnAppearing();
await LoadList();
}
c# 逻辑说“当前上下文中不存在名称‘HideButtonRef’”
解决方案
在要绑定的代码隐藏上创建一个属性。您必须确保 ViewModel 实现 INotifyPropertyChanged:
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
然后创建一个属性来保存是否显示按钮的值。
bool _isAdmin;
public bool IsAdmin
{
get {return _isAdmin;}
set
{
_isAdmin = value;
OnPropertyChanged("IsAdmin");
}
}
然后将 XAML 中的按钮定义更改为:
<Button x:Name="HideButtonRef"
Clicked="HideButton"
Text="{Binding stringVal}"
IsVisible="{Binding IsAdmin}"
HeightRequest="50" />
OnAppearing 现在变成了
protected override async void OnAppearing()
{
IsAdmin = !User.Admin;
base.OnAppearing();
await LoadList();
}
推荐阅读
- java - 使用 Cassandra 驱动程序的 Flink 应用程序中的 ClassNotFoundException 和 NoClassDefFoundError
- swift - 与 UITextField 相比,使用 UISearchBar 有什么优势?
- html - Docusign - 上传 HTML 模板
- svn - 如果我不小心将我的 svn 深度设置为立即数或空,未提交的文件会发生什么?
- excel - 使用 VBA 计算范围内彩色单元格的数量
- python - 如何使用 Selenium 和 Python 点击 span 元素
- python-3.x - pd.to_datetime 为零时不转换日期
- javascript - 在 HTML 模板中显示总价
- python - Python数据框删除只有索引没有单元格值的行
- php - laravel 7 错误 403 禁止在线网站