代码之家  ›  专栏  ›  技术社区  ›  EpicKip

带有集合的控件使用不正确的值类型样式

  •  0
  • EpicKip  · 技术社区  · 6 年前

    在WPF中包含集合的控件(例如 ListBox ComboBox 使用 TextBlock 使用值类型(如 int enum )

    可验证示例:

    XAML代码:

    <Window.Resources>
        <Style TargetType="ComboBox">
            <Setter Property="FontSize" Value="8"/>
            <Setter Property="Height" Value="25"/>
            <Setter Property="Foreground" Value="Green" />
        </Style>
    
        <Style TargetType="TextBlock">
            <Setter Property="FontSize" Value="50"/>
            <Setter Property="Foreground" Value="Red" />
        </Style>
    </Window.Resources>
    <Grid>
        <ComboBox Name="cbb1" Margin="0 -100 0 0"/>
        <ComboBox Name="cbb2"/>
    </Grid>
    

    CS代码:

    //In the constructor
    cbb1.ItemsSource = new[] { "A", "B", "C" };
    cbb1.SelectedItem = cbb1.Items[0];
    
    cbb2.ItemsSource = new[] { 1, 2, 3 };
    cbb2.SelectedItem = cbb2.Items[0];
    

    此示例代码将显示2 组合框 's,其中项具有'incorrect' 控件 造型和其他将有“正常” 组合框 造型。

    其他,然后为所需的值类型(最常见的是 枚举 对于我来说)或者删除样式是否有解决方法或修复方法?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Clemens    6 年前

    使用不使用默认文本块样式的textBlock声明itemTemplate:

    <Style TargetType="ComboBox">
        <Setter Property="FontSize" Value="8"/>
        <Setter Property="Height" Value="25"/>
        <Setter Property="Foreground" Value="Green" />
        <Setter Property="ItemTemplate">
            <Setter.Value>
                <DataTemplate>
                    <TextBlock Text="{Binding}"/>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>