问题描述
我正在使用 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,*" ColumnDeFinitions="75,*" Margin="15,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();
}