如何使用图像和文本填充xaml组合框

时间:2013-02-06 13:25:37

标签: xaml windows-8 microsoft-metro

我绑定了一个Xaml Combobox。我可以使用Stackpanel或List吗?你能解释一下如何以这种方式绑定数据吗?

1 个答案:

答案 0 :(得分:3)

首先,您需要一些带有公共属性的数据,以获取要与其一起显示的图像和文本的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来对图像进行一些尺寸限制。