1
我有一套用于自定义控件的数据模板。它运行良好,但我希望能够将其绑定到数据,并根据集的最小/最大值对值进行缩放。我创建了以下值转换器:操纵DataTemplate中的值转换器
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
}
理想的情况下,他们将我的模板的部分,我可以提取它们的零件,但似乎并没有工作。
任何人都可以指出我正确的方向,让这种行为工作吗?
问候
特里斯坦
编辑:我想这将是很好能够依赖注入他们。有谁知道这是否可能?
嗨,谢谢。这看起来应该可以完成这项工作,但是我在某种特定的实现上有些困难。 ScaleValueConverters绑定在ItemsControl的Item模板中,但他们需要访问父集以计算Min/Max。我怎样才能做到这一点? – Tristan 2012-07-31 08:53:46
我可能不会用转换器来处理这个问题,而是更新数据模型以包含最小值和最大值。另一种适用于复杂项目的方法是将其作为模板化控件进行构建。食物的思想。 – Brian 2012-08-01 12:15:11