开发者

WPF Databound Listbox

开发者 https://www.devze.com 2023-01-03 12:08 出处:网络
I have a listbox bound to a list of开发者_开发知识库 objects for a data entry screen. The item template includes textblocks, a checkbox and comboboxes.

I have a listbox bound to a list of开发者_开发知识库 objects for a data entry screen. The item template includes textblocks, a checkbox and comboboxes.

When the listbox is populated I would like to change the foreground color of the textblocks to red if object.value1 = true and object.value2 = 0.

Any ideas?


the following code works:

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>

Class

public class Model
{
    public Int32 Value1 { get; set; }
    public Int32 Value2 { get; set; }
    public String Text { get; set; }
}

Code

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;


Use MVVM, and have your view model expose a property which checks the condition, and returns the color. Then bind the foreground color to that property :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消