gpt4 book ai didi

c# - ComboBox:根据属性状态设置样式内容

转载 作者:太空宇宙 更新时间:2023-11-03 14:40:06 24 4
gpt4 key购买 nike

有些帖子可能指出了我的问题,但当我尝试将他们的解决方案应用到我的任务时,我又一次被其他问题困住了。

所以,我想要一个 ComboBox 来显示我的路径类中的数字 (PathID)。 Path有一个属性叫做PathState,它是一个enum,可以是PathState.red、PathState.blue、PathState.green,表示一种颜色。

我想创建一个简单的 Path 类型的硬编码列表,仅供学习之用,然后填充 ComboBox。我想创建三个 ID 递增的路径对象,通过分配 PathState 属性为每个对象赋予不同的颜色。

启动应用程序后,ComboBox 应由数字 1、2 和 3 组成,其中 1 是红色,2 是绿色,3 是蓝色。

我知道我需要通过 ComboBox.ItemTemplate、DataTemplate 和 DataTrigger 来访问它 - 我只是不知道从哪里开始。

public class Path
{
public int PathID {get;set;}
public PathState PathState { get; set;}
}

public enum PathState
{
red = 0,
green = 1,
blue = 2
}

编辑:好的,我已经做了一些努力,但是卡在了 DataTrigger-Part 上:这是我的代码:

<ComboBox Name="cmbTest" ItemsSource="{Binding MyPaths}" Grid.Column="1" Grid.Row="1"  VerticalContentAlignment="Center" HorizontalContentAlignment="Center">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock x:Name="cmbText" Text="{Binding PathId}" Foreground="Red"/>
</DataTemplate>
</ComboBox.ItemTemplate>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=MyPaths}" Value="MyPaths.PathState">
<!-- Actually, I don't know how to continue beyond this point) -->
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox>

最佳答案

您应该编写一个 IValueConverter,将您的 PathState 转换为相应的 System.Windows.Media.Brush。使用预定义的 Brushes( https://learn.microsoft.com/de-de/dotnet/api/system.windows.media.brushes?view=netframework-4.8 ),除非您需要一些特殊的东西。

然后在资源中的某处实例化值转换器(可以在任何父级,我只是为了这个例子把它放在 ComboBox 中。然后使用转换器将颜色绑定(bind)到显示属性。

如果您想要背景,请在ItemContainerStyle 中进行。如果你想要 Foreground 把它放在任何需要的地方。当心:我的示例设置了 Foreground=Background,您不会看到太多内容。

<ComboBox>
<ComboBox.Resources>
<local:MyColorConverter x:Key="colorConverter"/>
</ComboBox.Resources>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding PathID}" Foreground="{Binding PathState,Converter={StaticResource colorConverter}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="Background" Value="{Binding PathState,Converter={StaticResource colorConverter}}"/>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>

关于c# - ComboBox:根据属性状态设置样式内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57414563/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com