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