Search code examples
c#xamluwpobservablecollection

Binding data to a ListView inside user control (UWP)


I have a user control like this

  <Grid>
    <ListView SelectionMode="Multiple" x:Name="lview"  ItemsSource="{x:Bind ItemsSource, Mode=OneWay}" DisplayMemberPath="{x:Bind DisplayMemberPath}"  ></ListView>
</Grid>

Code behind

 public sealed partial class UserCntrl : UserControl
{
    public UserCntrl()
    {
        this.InitializeComponent();
    }

    public static readonly DependencyProperty ItemsSourceProperty =
     DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(UserControl),
         new PropertyMetadata(null));

    public IEnumerable ItemsSource
    {
        get => (IEnumerable)GetValue(ItemsSourceProperty);
        set => SetValue(ItemsSourceProperty, value);
    }

    public string DisplayMemberPath
    {
        get { return (string)GetValue(DisplayMemberPathProperty); }
        set { SetValue(DisplayMemberPathProperty, value); }
    }

    public static readonly DependencyProperty DisplayMemberPathProperty =
    DependencyProperty.Register("DisplayMemberPath", typeof(string), typeof(UserControl), new PropertyMetadata(""));

}

MainPage code

  <local:UserCntrl x:Name="lview"   Loaded="EditTextControl_Loaded"></local:UserCntrl>

Code behind

 public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

    private void EditTextControl_Loaded(object sender, RoutedEventArgs e)
    {
        ObservableCollection<OptionItem> io = new ObservableCollection<OptionItem>();

        io.Add(new OptionItem { Name = "11111111111" });
        lview.ItemsSource = io;
        lview.DisplayMemberPath = "Name";

    }
}

public class OptionItem 
{
    private string _Name = string.Empty;
    public string Name
    {
        get { return _Name; }
        set { _Name = value;  }
    }

}

This gives an output like this

enter image description here

How can I make this control display correct items it contains, instead of the name of the model. Complete code is available here. Note: I can't edit the model or the way I add content to the ObservableCollection. I have to make this work by editing the UC


Solution

  • Just use ItemTemplate for that:

    <ListView...>
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{x:Bind Name}" />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
    

    It gives you great flexibitlity, when it comes to how to display an item :)

    EDIT: Try defining dependency property for ItemTemplate

    public DataTemplate ItemTemplate
    {
        get { return (DataTemplate)GetValue(ItemTemplateProperty); }
        set { SetValue(ItemTemplateProperty, value); }
    }
    
    public static readonly DependencyProperty ItemTemplateProperty =
        DependencyProperty.Register("ItemTemplate", typeof(DataTemplate), typeof(UserControl));