开发者

Silverlight databinding - How do I dynamically change the style of elements based on previous elements?

开发者 https://www.devze.com 2023-02-10 20:05 出处:网络
I\'ve got a ListBox that contains an alphabetized list of words. For each let开发者_JAVA技巧ter, I\'d like the first word to be blue and all other words to be white. I\'d done this previously by loopi

I've got a ListBox that contains an alphabetized list of words. For each let开发者_JAVA技巧ter, I'd like the first word to be blue and all other words to be white. I'd done this previously by looping through the words, creating TextBlock controls with the appropriate Foreground color, and adding them manually to the ListBox control. I'd like to do this with databinding, though. Is there an elegant way to apply this sort of conditional formatting with databinding?


This is the sort of thing that you typically use a ViewModel for. What you could do is to create a WordViewModel class that looks something like this (but presumably with INotifyPropertyChanged implementations, etc.):

public class WordViewModel
{
    public string Word {get; set;}
    public Color ForegroundColor {get; set;}
}

When you add the WordViewModel instances to your ObservableCollection<WordViewModel>, you would then set the appropriate properties based on roughly the same logic you were using before.

Your ListBox would then look something like this:

<ListBox ItemsSource="{Binding MyWords}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Word}" ForegroundColor="{Binding ForegroundColor}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Having a "ForegroundColor" in a Model would of course be a complete violation of the "separation of concerns". It would be most appropriate in a View if there were a clean and easy way to do it. But given the circumstances, unless someone can think of a better way to handle it in XAML, I think it's reasonably appropriate to place it in the ViewModel.

0

精彩评论

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