WPF数据绑定列表框

时间:2010-06-16 14:31:44

标签: wpf listbox databound

我有一个列表框绑定到数据输入屏幕的对象列表。项目模板包括文本块,复选框和组合框。

当填充列表框时,如果object.value1 = true且object.value2 = 0,我想将文本块的前景色更改为红色。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

使用MVVM,让您的视图模型公开一个检查条件的属性,并返回颜色。然后将前景色绑定到该属性: - )

答案 1 :(得分:0)

以下代码有效:

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;