如何在主详细信息页面中设置列表视图的默认选定项目

时间:2018-06-16 23:17:14

标签: listview xamarin xamarin.forms

我正在引用Xamarin Master详细示例应用程序。在那里,我们在Master-Detail页面中使用ListView。我们想在MasterDetailPage的启动时将First Item设置为Selected Item。

MasterDetaiPagel Sample App Link

1 个答案:

答案 0 :(得分:0)

我发现处理此问题的最佳方法是停止依赖内置的ListView选择样式并自行处理选择背景。遗憾的是,禁用默认选择样式需要自定义渲染。

实施下面的ViewCell渲染器以禁用默认选择样式。然后,您只需将ViewCell子控件的BackgroundColor绑定到模型上的IsSelected属性,或者您想要如何执行此操作。

如果要设置默认选定项目:

mySelectedItem.IsSelected = true; //Assuming this bubbles up a PropertyChanged event to the ListView

MyListView.SelectedItem = mySelectedItem;
// Maybes scroll to the item here if necessary

以下代码并不完美,请告知我是否可以进行任何改进。

Xamarin表示ViewCell

public class CustomViewCell : ViewCell { }

Android ViewCell自定义渲染器

public class CustomViewCellRenderer : ViewCellRenderer {

    protected override View GetCellCore(Cell item, View convertView, ViewGroup parent, Context context) {
        View cellCore = base.GetCellCore(item, convertView, parent, context);

        if(parent is ListView listView) {
            listView.SetSelector(Android.Resource.Color.Transparent);
            listView.CacheColorHint = Color.White;
        }

        cellCore.SetBackground(GetUnpressedBackground());

        return cellCore;
    }


    private StateListDrawable GetUnpressedBackground() {
        StateListDrawable states = new StateListDrawable();
        //states.AddState(new[] { Android.Resource.Attribute.StatePressed }, new ColorDrawable(Color.White));
        //states.AddState(new[] { Android.Resource.Attribute.StateFocused }, new ColorDrawable(Color.White));
        //states.AddState(new int[] { }, new ColorDrawable(Color.Blue.ToAndroid()));

        return states;
    }
}

iOS ViewCell自定义渲染器

public class CustomViewCellRenderer : ViewCellRenderer {

    public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv) {
        UITableViewCell  cell = base.GetCell(item, reusableCell, tv);

        if(cell != null) {
            // Disable native cell selection color style - set as *Transparent*
            cell.SelectionStyle = UITableViewCellSelectionStyle.None;

            //cell.SelectedBackgroundView = new UIView(new RectangleF(0, 0, (float)cell.Bounds.Width, (float)cell.Bounds.Height)) {
            //    BackgroundColor = UIColor.Clear
            //};
        }

        return cell;
    }
}