multiple selection on custom picker C# UWP

允我心安 提交于 2019-12-25 12:52:12

问题


I've been looking on forums and internet about a custom picker on C#, I have a picker already functional, but some of my research throw me that you are only able to select 1 item of the custom Picker, this is the code im using to deploy the picker.

Picker

<custom:CustomPicker x:Name="pickerCategories" ItemsSource="{Binding listCategoriesName}" SelectedIndex="{Binding SelectedCategory}" SelectedIndexChanged="pickerCategories_SelectedIndexChanged" Grid.Column="1" BackgroundColor="White"/>

the item source are given to the picker as a list of object from a database is there a way to be able to select multiple index of the custom picker? for Example...

Picker pk = new Picker(); pk.SelectionMode=Multiple; 

回答1:


For you requirement, you could make a custom Picker renderer in the native uwp project. And then make a new DataTemplate for displaying ComboBox item that contain checkbox in the native control.

<DataTemplate x:Key="templateEmployee" >
    <StackPanel  Orientation="Horizontal">
        <CheckBox Content="{Binding Content,Mode=TwoWay}" IsChecked="{Binding IsCheck,Mode=TwoWay}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
    </StackPanel>
</DataTemplate>

For CustomPickerRenderer, you should pass the Forms Picker item source to native control(ComboBox). And when combobox drop down closed, you could execute InvokeAction method to send Data to the Forms Picker.

public class CustomPickerRenderer : PickerRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
    {
        base.OnElementChanged(e);
        Control.ItemsSource = e.NewElement.ItemsSource;
        Control.ItemTemplate = (Windows.UI.Xaml.DataTemplate)App.Current.Resources["templateEmployee"];
        Control.DropDownClosed += Control_DropDownClosed;

    }

    private void Control_DropDownClosed(object sender, object e)
    {
        var NewElement = Element as CustomPicker;
        var items = (sender as ComboBox).ItemsSource;
        NewElement.InvokeAction(items);
    }

}

Usage

public MainPage()
{
    InitializeComponent();
    MyPicker.ItemsSource = new MainViewModel().itemSource;
    MyPicker.RegisterAction(IsCheckItems);
}
private List<Item> SelecItms = new List<Item>();
private void IsCheckItems(object data)
{
    var items = data as ObservableCollection<Item>;
    var str = new StringBuilder();
    foreach (var item in items)
    {
        if (item.IsCheck)
        {
            SelecItms.Add(item);
            str.AppendLine(item.Content);
        }
    }
    SeleitemLabel.Text = str.ToString();
}

And I have uploaded the code sample. Please check.



来源:https://stackoverflow.com/questions/47165019/multiple-selection-on-custom-picker-c-sharp-uwp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!