将数据绑定到用户控件(UWP)内的ListView中

问题描述 投票:0回答:2

我有这样的用户控件

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

后面的代码

 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(""));

}

主页代码

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

后面的代码

 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;  }
    }

}

这给出了这样的输出

enter image description here

如何使此控件显示其包含的正确项目,而不是模型的名称。完整代码可用here。注意:我无法编辑模型或将内容添加到ObservableCollection的方式。我必须通过编辑UC来完成这项工作

c# xaml uwp observablecollection
2个回答
1
投票
[在显示项目时,它具有很大的灵活性:)

EDIT
© www.soinside.com 2019 - 2024. All rights reserved.