2016-10-16 135 views
0

我想在Silverlight組合框中顯示圖像和文本。我在WPF中用ItemTemplate在圖像和名稱中顯示顏色時找到了一個示例。 在Silverlight中,相同的xml結果爲空行。因此,對於每個項目都有一個項目生成,它只是不綁定到Name屬性。 Silverlight是否需要其他綁定而不是WPF?Silverlight組合框項目模板綁定

這是樣板:

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> 

回答

0

試圖通過結合Color的名稱將無法正常工作設置RectangleFill。 XAML中做了一些特殊的魔力來獲得:

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

工作。因此,從GetProperties()返回的PropertyInfo的「Name」屬性爲「Black」,「white」或「Yellow」,但不能直接使用它。你需要做的是創建一個名稱和畫筆字典,併爲每個人分配一種不同的顏色,然後將你的ComboBox的DataSource綁定到那個。

此代碼:

的.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> 
相關問題