【问题标题】:silverlight combobox itemtemplate bindingsilverlight 组合框项目模板绑定
【发布时间】:2016-10-16 16:18:24
【问题描述】:

我想在 Silverlight ComboBox 中显示图像和文本。我在 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>

【问题讨论】:

    标签: c# silverlight combobox datatemplate itemtemplate


    【解决方案1】:

    尝试通过绑定到 Color 的名称来设置 RectangleFill 是行不通的。 XAML 做了一些特殊的魔法来获得:

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

    工作。因此,虽然从 GetProperties() 返回的 PropertyInfo 的“名称”属性是“黑色”、“白色”或“黄色”,但您不能直接使用它。您需要做的是创建一个包含名称和画笔的字典,并为每一个分配不同的颜色,然后将您的组合框的 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多