我有一个列表框绑定到数据输入屏幕的对象列表。项目模板包括文本块、复选框和组合框。
填充列表框后,如果 object.value1 = true 且 object.value2 = 0,我想将文本块的前景色更改为红色。
有任何想法吗?
使用 MVVM,并让您的视图模型公开一个检查条件并返回颜色的属性。然后将前景色绑定到该属性:-)
以下代码有效:
XAML
<ListBox Name="ListBox1">
<ListBox.ItemTemplate>
<DataTemplate>
<DataTemplate.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Value1}"
Value="1" />
<Condition Binding="{Binding Value2}"
Value="0" />
</MultiDataTrigger.Conditions>
<MultiDataTrigger.Setters>
<Setter TargetName="RootBorder"
Property="Border.Background"
Value="#EEE" />
</MultiDataTrigger.Setters>
</MultiDataTrigger>
</DataTemplate.Triggers>
<Border Name="RootBorder">
<TextBlock Text="{Binding Text}" />
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
班级
public class Model
{
public Int32 Value1 { get; set; }
public Int32 Value2 { get; set; }
public String Text { get; set; }
}
代码
models.Add(new Model() { Value1 = 0, Value2 = 0, Text = "Item #1" });
models.Add(new Model() { Value1 = 1, Value2 = 0, Text = "Item #2" });
models.Add(new Model() { Value1 = 0, Value2 = 1, Text = "Item #3" });
models.Add(new Model() { Value1 = 0, Value2 = 0, Text = "Item #4" });
models.Add(new Model() { Value1 = 1, Value2 = 0, Text = "Item #5" });
models.Add(new Model() { Value1 = 0, Value2 = 1, Text = "Item #6" });
models.Add(new Model() { Value1 = 0, Value2 = 0, Text = "Item #7" });
models.Add(new Model() { Value1 = 1, Value2 = 0, Text = "Item #8" });
models.Add(new Model() { Value1 = 1, Value2 = 1, Text = "Item #9" });
ListBox1.ItemsSource = models;