【问题标题】:How to set master details page with option selected in xamarin.forms?如何使用 xamarin.forms 中选择的选项设置主详细信息页面?
【发布时间】:2019-09-13 08:16:03
【问题描述】:

我正在使用 Master 详细信息页面创建应用程序。在那方面,我错过了一件事情,那就是当我打开一个应用程序时,这里没有选择第一项。 我尝试使用不同的解决方案,例如制作“自定义视图单元”并制作一个渲染器来解决这个问题,但也出现了同样的问题。

我还提到了下面的图片。

有什么解决办法吗?

【问题讨论】:

标签: xaml xamarin xamarin.forms master-pages


【解决方案1】:

有点复杂,完全可以在Forms项目中完成,无需自定义渲染器。

我列出了实现您想要的步骤。

  1. 赋予模型属性以指示选择了哪一个并实现`INotifyPropertyChanged。

    public class MasterPageItem  : INotifyPropertyChanged
    {
        private bool isSelected;
        public bool IsSelected {
            get {
                return isSelected;
            }
            set {
                if (value != this.isSelected)
                {
                    this.isSelected = value;
                    NotifyPropertyChanged();
                }
            } 
        }
    }
    
  2. 在ViewCell中与父视图的背景颜色绑定,在Converter中将bool值转换为颜色

                <ViewCell>
                    <Grid Padding="5,10" BackgroundColor="{Binding IsSelected , Converter={StaticResource BooltoColor}}">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="30"/>
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>
                        <Image Source="{Binding IconSource}" />
                        <Label Grid.Column="1" Text="{Binding Title}" />
                    </Grid>
                </ViewCell>
    
    public class BooltoColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Color color ;
    
            if(((bool)value) == true)
            {
                color = Color.Gray;
            }
            else
            {
                color = Color.Transparent;
            }
    
            return color;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return true;
        }
    }
    
  3. 当您点击列表视图项目时,将项目设置为选中并取消选择其他项目。

    private void ListView_ItemTapped(object sender, ItemTappedEventArgs e)
    {
        foreach (MasterPageItem i in list)
        {
            i.IsSelected = false;
        }
    
        MasterPageItem item = e.Item as MasterPageItem;
        if (item != null)
        {
            item.IsSelected = true;
            list.RemoveAt(e.ItemIndex);
            list.Insert(e.ItemIndex, item);
        }
    }
    

在下面查看我的测试图片和示例链接

https://github.com/ColeXm/MasterDetailedSample/blob/master/Xamarin_Forms___MasterDetailPage.zip

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多