亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

ComboBox:根據屬性狀態設置內容樣式

ComboBox:根據屬性狀態設置內容樣式

C#
拉風的咖菲貓 2023-08-20 09:58:21
有一些帖子可能指出了我的問題,但是當我嘗試將他們的解決方案應用于我的任務時,我再次遇到了其他問題。所以,我想要一個 ComboBox 顯示我的 Path 類中的數字(PathID)。Path有一個屬性叫PathState,它是一個枚舉,可以是PathState.red、PathState.blue、PathState.green,表示一種顏色。我想創建一個簡單的路徑類型硬編碼列表,僅供學習之用,然后填充組合框。我想創建三個 ID 不斷增加的 Path 對象,通過分配 PathState 屬性為每個對象賦予不同的顏色。啟動應用程序后,組合框應包含數字 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>
查看完整描述

1 回答

?
海綿寶寶撒

TA貢獻1809條經驗 獲得超8個贊

您應該編寫一個IValueConverter從您的轉換PathState為相應的System.Windows.Media.Brush.?使用預定義的Brushes,除非您需要特殊的東西。

然后在資源中的某個位置實例化值轉換器(可以在任何父級別,我僅將其放入ComboBox本示例中。然后使用轉換器將顏色綁定到顯示屬性。

如果你想要Background,就在 之內做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>


查看完整回答
反對 回復 2023-08-20
  • 1 回答
  • 0 關注
  • 142 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號