【发布时间】:2020-05-18 06:50:02
【问题描述】:
我有一个这样的用户控件
<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; }
}
}
这给出了这样的输出
如何使此控件显示它包含的正确项目,而不是模型的名称。 完整代码可在here 获得。 注意:我无法编辑模型或向 ObservableCollection 添加内容的方式。我必须通过编辑 UC 来完成这项工作
【问题讨论】:
-
尝试在您的 UserControl 构造函数中添加
this.DataContext = this。 -
@Eldar 尝试不工作
标签: c# xaml uwp observablecollection