你能分享 UnitViewModel 的代码定义吗?请记住,绑定仅适用于属性,而不适用于打开的字段。我尝试了您的代码并为 Units 创建了一些基本的结构字段。那些没有用。所以,我猜你可能使用的是字段而不是属性:
public class MainViewModel
{
public MainViewModel()
{
Units = new ObservableCollection<UnitViewModel>();
Units.Add(new UnitViewModel
{
ID = "1",
Degrees = "80",
IsMaster = true
});
for (int i = 0; i < 10; i++)
Units.Add(new UnitViewModel
{
ID = "2",
Degrees = "40",
IsMaster = false
});
}
public ObservableCollection<UnitViewModel> Units {
get;
set;
}
}
public struct UnitViewModel
{
public string ID { get; set;}
public string Degrees { get; set;}
public bool IsMaster { get; set;}
}
}
我最后尝试了这段代码,没有任何问题。
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="WpfApplication1.MainWindow"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" d:DesignWidth="704">
<Window.Resources>
<local:MainViewModel x:Key="DesignViewModel" />
<DataTemplate x:Key="DataTemplate2">
<Grid >
<TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding ID}" VerticalAlignment="Top"/>
</Grid>
</DataTemplate>
</Window.Resources>
<Grid d:DataContext="{StaticResource DesignViewModel}">
<ItemsControl HorizontalAlignment="Left" Height="450" VerticalAlignment="Top" Width="632" ItemsSource="{Binding Units}"
/>
</Grid>
</Window>
添加 ItemTemplate 以正确设置数据表示的样式。