wpf - datatriggers repeated use
I have the开发者_JAVA百科 current DataTrigger:
<DataTrigger Binding="{Binding HeaderType}" Value="1">
<Setter Property="BorderThickness" Value="5"/></DataTrigger>
I want to do the same with values 2-100
Do I have to copy the Data Trigger 99 times or maybe there's a better way ?
Add a property to your view model:
public bool HasImportantHeader // or something...
{
get { return HeaderType >=1 && HeaderType <= 100; }
}
Use that property in the data trigger:
<DataTrigger Binding="{Binding HasImportantHeader}" Value="True">
<Setter Property="BorderThickness" Value="5"/>
</DataTrigger>
Generally, I like to keep my XAML as simple as possible, put all the logic in the view model, and avoid using Converters unless they are absolutely necessary.
Let's say you add another view, where you want to use bold text to indicate the header type is between 1 and 100. Just re-use the HasImportantHeader
property, something like:
<DataTrigger Binding="{Binding HasImportantHeader}" Value="True">
<Setter Property="FontWeight" Value="Bold"/>
</DataTrigger>
Later, you may decide that all header types up to 200 should have thick border and bold text. It'll be a simple matter of changing the implementation of the HasImportantHeader
property.
I've used this in similar situations
<DataTrigger Binding="{Binding HeaderType,
Converter={StaticResource RangeConverter},
ConverterParameter=1-100}"
Value="True">
<Setter Property="BorderThickness" Value="5"/>
</DataTrigger>
And in the converter we return true or false depending on the ranges
public class RangeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string[] ranges = parameter.ToString().Split(new char[]{'-'});
int headerType = (int)value;
if (headerType >= System.Convert.ToInt32(ranges[0]) &&
headerType <= System.Convert.ToInt32(ranges[1]))
{
return true;
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
You need to use a converter for that purpose.You can add a converter on your DataTrigger. The Converter will allow you to pass in the value, and return true or false.
<DataTrigger
Binding="{Binding HeaderType, Converter={StaticResource RengeConvertor}}"
Value="true"
>
<Setter Property="BorderThickness" Value="5" />
</DataTrigger>
and your converter should look something like
public class RengeConvertor : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int data = (int)value;
if (data >= 2 && data <= 100)
return true;
else
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
You may also find this interesting http://zamjad.wordpress.com/2010/07/29/range-converter/
精彩评论