首先 myOrders 必须是公共财产。即使它是一个公共变量也看不到它,其次是让视图(XAML)知道你需要DataContext = this;
在窗口的构造函数中设置的代码中发生了什么
设置这样的属性:public List<Order> myOrder {get;set;}
如果您需要从后面的代码更新视图,那么您需要实现INotifyPropertyChanged
接口。它负责更新视图工作。这是来自 MSDN 的一个小教程。
最后一件事,(根据我的经验)你应该使用 type 属性ObservableCollection<Order>
而不是List<Order>
.
XAML:
<Grid>
<ItemsControl x:Name="visual"
ItemsSource="{Binding MyOrders}"
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Stretch">
<ItemsControl.ItemTemplate>
<!-- This defines the DataTemplate to display one Order object-->
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding OrderName}"
Margin="10" />
<ItemsControl ItemsSource="{Binding PartsList}"
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Stretch">
<ItemsControl.ItemTemplate>
<!-- This defines the DataTemplate to display one Parts object-->
<DataTemplate>
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
Text="{Binding PartName}"
TextAlignment="Center" />
<TextBlock Grid.Column="1"
Text="{Binding PartQuantity}"
TextAlignment="Center" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
后面的代码:
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
public ObservableCollection<Order> MyOrders
{
get { return _myOrders; }
set { _myOrders = value; OnPropertyChanged("MyOrders"); }
}
Order order1 = new Order
{
OrderName = "Order1",
PartsList = new List<Parts>()
{
new Parts {PartName = "Part11", PartQuantity = 11},
new Parts {PartName = "Part12", PartQuantity = 12}
}
};
private ObservableCollection<Order> _myOrders;
public MainWindow()
{
InitializeComponent();
MyOrders = new ObservableCollection<Order>();
MyOrders.Add(order1);
DataContext = this;
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public class Order
{
public string OrderName { get; set; }
public List<Parts> PartsList { get; set; }
}
public class Parts
{
public string PartName { get; set; }
public double PartQuantity { get; set; }
}
}