组合框项目模板和前景
我有一个组合框,它绑定到我的视图模型中的字符串列表。我想做的是,如果我的 viewModel 中的属性为 true,则将组合框项的前景设置为不同的颜色:
<ComboBox x:Name="myComboBox" ItemsSource="{Binding Names}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ...}">
<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>
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
我不确定将 TextBlock 的文本绑定到什么。我想要的只是显示字符串列表。我总是最终得到一个包含项目的下拉菜单,但它们不可见。我尝试删除风格触发器,认为也许我搞砸了,但这没有帮助。
我采取的方法正确吗?在搜索 IsActive 时,ComboBox.ItemTemplate 是否会正确查看我的 viewModel(即数据上下文),或者该绑定是否也不正确?
I have a comboBox that is bound to a list of strings from my viewModel. What I am trying to do is have the foreground of a comboBox item be set to a different color if a property in my viewModel is true:
<ComboBox x:Name="myComboBox" ItemsSource="{Binding Names}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ...}">
<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>
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
I am not sure what to bind the Text of the TextBlock to. All I want is to display the list of strings. I always end up with a dropdown that has the items but they are not visible. I tried removing the style trigger thinking that maybe I was screwing up there, but that didn't help.
Am I taking the right approach? Will the ComboBox.ItemTemplate correctly look at my viewModel (which is the data context) when searching for IsActive or is that binding incorrect as well?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
每个
ComboBoxItem
的DataContext
都是一个字符串,因此TextBlock
,请像Text 一样绑定到
DataContext
="{Binding}为了使
DataTrigger
能够找到IsActive
,请在绑定中使用RelativeSource
The
DataContext
for eachComboBoxItem
is a string soTextBlock
, bind to theDataContext
likeText="{Binding}
For the
DataTrigger
to be able to findIsActive
, useRelativeSource
in the binding