鉴于以下内容,我如何只在DeviceListBox中显示DeviceName属性?
namespace NotMyNS
{
public class Device
{
public int SerialNumber { get; set; }
public string DeviceName { get; set; }
}
}
namepace MyNS
{
public partial class myControl : UserControl
{
public ObservableCollection<NotMyNS.Device> DeviceList { get; set; }
}
}
<UserControl x:Class="MyNS.myControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid >
<ListBox Name="DeviceListBox" />
</Grid>
</UserControl>
我看了很多例子,但未能适应我所看到的问题。
答案 0 :(得分:1)
您应该使用DisplayMemberPath
:
<ListBox Name="DeviceListBox" ItemsSource="{Binding DeviceList}" DisplayMemberPath="DeviceName" />
答案 1 :(得分:0)
您可以将ItemsControl.DisplayMemberPath
设置为要从视图模型中显示的属性。此外,如果您要将DeviceList
用作ItemsSource
,则需要将绑定上下文指定为UserControl
<ListBox
ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DeviceList}"
DisplayMemberPath="DeviceName" />
答案 2 :(得分:0)
在这种情况下。您需要在DataTemplate
内创建ListBox.ItemsSource
。创建TextBlock
并将其绑定到DeviceName。
答案 3 :(得分:0)
您还必须设置DataContext。添加“DataContext = this;”到myControl构造函数。 或者你可以这样做,而无需设置DataContext
<ListBox Name="DeviceListBox" ItemsSource="{Binding RelativeSource={RelativeSource
FindAncestor,AncestorType={x:Type Window}},Path=DeviceList}" DisplayMemberPath="DeviceName"/>