【发布时间】:2013-02-06 13:25:37
【问题描述】:
我正在绑定一个 Xaml 组合框。我可以使用 Stackpanel 或 List 吗?你能解释一下如何以这种方式绑定数据吗?
【问题讨论】:
标签: xaml windows-8 microsoft-metro
我正在绑定一个 Xaml 组合框。我可以使用 Stackpanel 或 List 吗?你能解释一下如何以这种方式绑定数据吗?
【问题讨论】:
标签: xaml windows-8 microsoft-metro
首先,您需要一些具有公共属性的数据,这些数据是您想要显示的图像和文本的 URI。下面是一个简单的例子:
public class ImageOption
{
public string ImageUri { get; set; }
public string ImageText { get; set; }
}
然后,您将需要另一个公共属性来保存该数据项的一些集合。此属性需要位于可以在视图中某处设置为 DataContext 或可以在代码隐藏中直接分配给 ComboBox 的对象上:
public ObservableCollection<ImageOption> ImageList { get; private set; }
假设 ComboBox 的某些父元素的 DataContext 已分配给包含 ImageList 属性的对象,那么您可以使用它来绑定集合并为每个项目显示一个简单的图像和文本:
<ComboBox ItemsSource="{Binding ImageList}">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Source="{Binding Path=ImageUri}" />
<TextBlock Text="{Binding Path=ImageText}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
您可能还希望通过设置 MaxWidth 和/或 MaxHeight 对图像进行一些尺寸限制。
【讨论】: