您不会将任何数据(无论这意味着什么)“附加”到 WPF 中的任何 UI 元素,仅仅是因为 UI is not Data。
如果您使用 WPF,您确实需要了解 The WPF Mentality,这与其他技术中使用的其他方法非常不同。
在 WPF 中,您使用 DataBinding 将 UI“绑定”到数据,而不是在 UI 中“放置”或“存储”数据。
这是一个示例,说明如何将 ListBox 绑定到 WPF 中的数据项集合:
XAML:
<ListBox ItemsSource="{Binding MyCollection}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding FirstName}"/>
<TextBlock Text="{Binding LastName}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
视图模型:
public class MyViewModel
{
public ObservableCollection<MyData> MyCollection {get;set;}
//methods to create and populate the collection.
}
数据项:
public class MyData
{
public string LastName {get;set;}
public string FirstName {get;set;}
}
我强烈建议您在开始使用 WPF 编码之前阅读 MVVM。否则你会很快碰壁并在不需要的代码上浪费太多时间。