[英]Manipulating Value Converters inside 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
}
理想情況下,它們應該是模板的一部分,我可以將它們提取為一部分,但這似乎行不通。
誰能指出我正確的方向,以使這種行為有效?
問候
特里斯坦
編輯:我想能夠依賴注入它們會很好。 有人知道這是否可能嗎?
從DependDencyObject派生ScaleValueConverter並將您的屬性實現為Dependency Properties。
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}" />
簡而言之,將轉換器與任何其他依賴項對象一樣對待,並照常進行綁定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.