Reputation: 33
I'm trying to create a dynamic list in WPF using ListView. My code reads in a file and will import it into this list to be displayed. My intent is that every time a tab character is seen in the string, the row's font size will decrease by 4 (starting at a font size of 24). So all strings with no tabs will be at 24, all strings with 1 tab at 20, all strings at 2 tabs 16 and so on). I would ideally like to set the row styling every time I add a row to the list (at least, I think that would be the easiest).
So, ideally I would see something like this:
String(Font Size 24)
String(Font Size 20)
String(Font Size 16)
String(Font Size 20)
String(Font Size 16)
And so on.....
I'm very new to WPF and am finding it very difficult to manipulate it using XAML at the moment. I can't seem to find the command to make each row individualized for style.
Upvotes: 3
Views: 1221
Reputation: 61369
First, we need to set up an ItemTemplate
to house our styled control
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock>
<DataTemplate>
</ListView.ItemTemplate>
Second, what is FontSize
dependent on? The string itself. This means that we need to bind it in the item template:
<TextBlock FontSize="{Binding Text}"/> //Could be "." if binding to List<String>
Note that we can do this because FontSize
is a Dependency Property. Finally, the text is obviously not a number, so we need a converter to change it to one:
<TextBlock FontSize="{Binding Path=Text,
Converter={StaticResource TabCountStringConverter}}"/>
public class TabCountStringConverter : IValueConverter
{
public object Convert(...)
{
return (value as String).Count(c => c == '\t'); //Count tabs
}
public object ConvertBack(...)
{
return Binding.DoNothing;
}
}
I make no claims for my tab counting function, but its a good start :) It needs an element to change the tab count into the correct font size, a Dictionary
perhaps. The implementation is really up to you.
You could also set this on the row "container" control, as it should apply to the nested controls as well. See MSDN.
To try and clear up confusion from the comments:
"Path=." means "Bind to the object itself". Since you already have the string in question as the data context, you don't want to bind to a property of it, you want to bind to the string.
Static resources must be defined in the Resources
collection of your container; for example:
<UserControl.Resources>
<local:TabCountStringConverter x:Key="TabCountStringConverter"/>
</UserControl.Resources>
Where "local" was previously defined as an xmlns
. The return value of the converter is used when evaluating the binding, what we are doing here is telling the framework which converter to use. If we don't make one (as seen above) you will get a resource not found exception.
Upvotes: 2