Conditionally changing the Foreground of a WPF ComboBox item depending upon a value in the databound ItemsSource item

為{幸葍}努か 提交于 2019-12-08 01:41:17

问题


I have a WPF ComboBox bound to a Collection List<Users>. I have applied a DataTemplate to show the FirstName using a TextBlock and this works as expected:

        <ComboBox Margin="5" ItemsSource="{Binding Path=TheUsers}" Name="cboUsers">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Margin="10" Text="{Binding Path=FirstName}">
                    </TextBlock>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>`

I have an item in my User class called IsActive which is a Boolean value. If true then I want to set the Foreground of the TextBlock to Navy.

I have spent so much time on what should be so easy and looked all over the web but most articles talk about changing the overall colour or binding to another element in the xaml.

I tried implementing a DataTrigger and after an hour removed the code because it was not working. It would not recognise my field name. Does anyone have a very simple guide to how to do this or what would be the best approach?


回答1:


As you apparently are not dealing with fields after all, this style should do what you want:

<TextBlock.Style>
    <Style TargetType="{x:Type TextBlock}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding IsActive}" Value="True">
                <Setter Property="Foreground" Value="Navy"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</TextBlock.Style>

It would not recognise my field name.

You cannot bind to fields, end of story.



来源:https://stackoverflow.com/questions/5890159/conditionally-changing-the-foreground-of-a-wpf-combobox-item-depending-upon-a-va

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!