簡體   English   中英

silverlight組合框itemtemplate綁定

[英]silverlight combobox itemtemplate binding

我想在Silverlight組合框中顯示圖像和文本。 我在WPF中找到一個示例,其中的ItemTemplate通過圖像和名稱顯示顏色。 在Silverlight中,相同的xml導致空行。 因此,對於每個項目,都會生成一個項目,但它不會綁定到Name屬性。 Silverlight是否需要WPF以外的其他綁定?

這是示例:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        cmbColors.ItemsSource = typeof(Colors).GetProperties();
    }
}

XML格式

<UserControl x:Class="SilverlightColors.MainPage"
    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"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <StackPanel >
            <ComboBox Name="cmbColors" >
                <ComboBox.ItemTemplate  >
                    <DataTemplate  >
                        <StackPanel Orientation="Horizontal">
                            <Rectangle Fill="{Binding Name}" Width="16" Height="16" Margin="0,2,5,2"/>
                            <TextBlock Text="{Binding Name}"/>
                        </StackPanel>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>
        </StackPanel>
    </Grid>
</UserControl>

試圖通過綁定到Color名稱來設置“ Rectangle Fill ”將不起作用。 XAML做一些特殊的魔術來獲取:

<Rectangle Fill="White" Width="16" Height="16" Margin="0,2,5,2"/>

上班。 因此,雖然從GetProperties()返回的PropertyInfo的“名稱”屬性是“黑色”,“白色”或“黃色”,但是您不能直接使用它。 您需要做的是創建一個名稱和畫筆的字典,為每個畫筆分配不同的顏色,然后將組合框的數據源綁定到該顏色。

此代碼有效:

.cs:

var list = typeof(Colors).GetProperties();
var brushes = new Dictionary<string, SolidColorBrush>();
foreach (var colour in list)
{
    brushes.Add(colour.Name, new SolidColorBrush((Color)colour.GetValue(colour, null)));
}
cmbColors.ItemsSource = brushes;

XAML:

<ComboBox Name="cmbColors"
          VerticalAlignment="Center"
          HorizontalAlignment="Center">
    <ComboBox.ItemTemplate  >
        <DataTemplate  >
            <StackPanel Orientation="Horizontal">
                <Rectangle Fill="{Binding Value}" Width="16" Height="16" Margin="0,2,5,2"/>
                <TextBlock Text="{Binding Key}"/>
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM