操纵DataTemplate中的值转换器

时间:2012-07-30 15:52:47

标签: silverlight ivalueconverter valueconverter template-control

我有一组用于自定义控件的数据模板。它运行良好,但我希望能够将其绑定到数据并根据集合的最小值/最大值进行值缩放。我创建了以下值转换器:

    public class ScaleValueConverter : IValueConverter
{
    /// <summary>
    /// The property to use the value of
    /// </summary>
    public string ValueProperty { get; set; }

    /// <summary>
    /// The minimum value to be scaled against. Will become 0%
    /// </summary>
    public int MinValue { get; set; }

    /// <summary>
    /// The maximum value to be scaled against. Will become 100%.
    /// </summary>
    public int MaxValue { get; set; }


    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var type = value.GetType();
        var property = type.GetProperty(ValueProperty);

        if (property == null)
            return 0;

        var result = System.Convert.ToDecimal(property.GetValue(value, null));

        //TODO: Scale stuff

        return result + 100;
    }

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

    #endregion
}

目标是拥有一个通用值转换器,并简单地将绑定源对象提供给XAML中的值转换器,并对其进行排序。

我不知道该怎么做,因为我无法访问我从模板化控件创建的值转换器。

我正在寻找可以大致如下工作的东西:

        public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        //Get Value Converters
        var topScaleValueConverter = GetTemplateChild("TopScaleValueConverter");
        var bottomScaleValueConverter = GetTemplateChild("BottomScaleValueConverter");

        //Setup value converter Min / Max / ValueProperty here
    }

理想情况下,它们将成为我模板的一部分,我可以将它们作为部分提取出来,但这似乎不起作用。

有人能指出我正确的方向让这种行为发挥作用吗?

此致

特里斯坦

编辑:我想能够依赖注入它们会很好。有谁知道这是否可行?

1 个答案:

答案 0 :(得分:0)

从DependDencyObject派生ScaleValueConverter,并将您的属性实现为依赖属性。

  public class ScaleValueConverter : DependencyObject, IValueConverter
    {

        public double MinValue
        {
            get { return (double)GetValue(MinValueProperty); }
            set { SetValue(MinValueProperty, value); }
        }

        public static readonly DependencyProperty MinValueProperty =
            DependencyProperty.Register("MinValue", typeof(double), typeof(ScaleValueConverter), new PropertyMetadata(0.0d));


        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            double result = double.Parse(value.ToString())

            if (result < MinValue)
            {
                result = MinValue;
            }

          return result;
        }
    }

然后,您就可以通过VM将数据“注入”到您的属性中。

<ns:ScaleValueConverter x:Key="scaleValue" MinValue="{Binding MinValue,Source={StaticResource MyModelSource}" />

简而言之,将转换器视为与任何其他依赖项对象相同,并照常绑定。