在BorderThickness中使用String Format绑定int属性

时间:2015-03-30 12:13:55

标签: c# wpf templates string-formatting

我有一个带有自己属性BorderWidth的模板:

public static readonly DependencyProperty BorderWidthProperty = DependencyProperty.Register("BorderWidth", typeof(int), typeof(ProjectOverviewSensor), new PropertyMetadata(1));

现在我想在我的模板中使用StringFormat将此属性绑定到BorderThickness,以创建特定边的边框。但它在所有四个方面都是1个。

<Border BorderThickness="{Binding Path=BorderWidth, RelativeSource={RelativeSource TemplatedParent}, StringFormat='{}{0},0,{0},0'}"></Border>

我如何才能将属性绑定到边界控制的两侧,我想要?有没有替代stringformat?

2 个答案:

答案 0 :(得分:0)

Binding.StringFormat仅适用于System.String类型的属性。

与XAML编写的字符串不同,因为在这里,XAML解析器在解析过程中将字符串转换为厚度值。

要做你想做的事,你需要一个转换器来绑定:

class MyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if(value == DependencyProperty.UnsetValue)
            return value;
        return new Thickness((int)value,0, (int)value, 0);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((Thickness)value).Left;
    }   
}

并像这样使用:

<Window.Resources>
    <MyConverter x:Key="ToThickness"/>
</Window.Resources>
<Border BorderThickness="{Binding Path=BorderWidth, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource ToThickness}"></Border>

答案 1 :(得分:0)

现在我创建了一个扩展转换器,我希望他不要向你隐瞒。

public class CustomThicknessConverter : IValueConverter
{
    protected readonly char SplitChar = ',';
    protected readonly char ReplaceAt = '#';

    /// <summary>
    /// Create a thickness with custom format(for example #,2,#,5).
    /// </summary>
    /// Number for default width.
    /// # for given border width.
    /// ; for split the chars.
    /// For example '#,0,#,0' with 1 as value return a new thickness 
    /// with Left = 1, Top = 0, Right = 1, Bottom = 0.
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if(value == DependencyProperty.UnsetValue)
            return value;

        var borderWidth = value as double?;
        var format = parameter.ToString().Split(SplitChar); 

        if(format.Length == 1)
            return new Thickness(GetValue(borderWidth, format[0]));

        else if(format.Length == 2)
        {
            return new Thickness()
            {
                Left    = GetValue(borderWidth, format[0]),
                Top     = GetValue(borderWidth, format[1]),
                Right   = GetValue(borderWidth, format[0]),
                Bottom  = GetValue(borderWidth, format[1])
            };
        }

        else if(format.Length == 4)
        {
            return new Thickness()
            {
                Left    = GetValue(borderWidth, format[0]),
                Top     = GetValue(borderWidth, format[1]),
                Right   = GetValue(borderWidth, format[2]),
                Bottom  = GetValue(borderWidth, format[3])
            };
        }

        return new Thickness(0);
    }

    private double GetValue(double? value, string format)
    {
        if(format.FirstOrDefault() == ReplaceAt) return value ?? 0;

        double result;
        return (Double.TryParse(format, out result)) ? result : 0;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

在xaml:

<local:CustomThicknessConverter x:Key="CustomThicknessConverter" />    
<Border BorderThickness="{Binding BorderWidth, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource CustomThicknessConverter}, ConverterParameter='0,#,0,#'}">

</Border>