绑定到转换器参数

是否有可能绑定到Silverlight 4.0中的ConverterParameter?

例如,我想要做这样的事情,并将ConverterParameter绑定到ViewModel中的对象。

如果这是不可能的,还有其他的select吗?

<RadioButton Content="{Binding Path=Mode}" IsChecked="{Binding Converter={StaticResource ParameterModeToBoolConverter}, ConverterParameter={Binding Path=DataContext.SelectedMode,ElementName=root}}" /> 

不幸的是,你不能绑定到一个ConverterParameter。 我以前使用过两个选项:不是使用Converter,而是在您的ViewModel(或任何绑定的)上创build一个属性,为您进行转换。 如果你仍然想要转换路由,将整个绑定对象传递给转换器,然后你可以这样做你的计算。

另一种select是通过创build一个自定义的转换器来包装你的其他转换器,并从一个属性传递一个转换器参数。 只要这个自定义转换器inheritance了DependencyObject并使用了一个DependencyProperty,它就可以被绑定。 例如:

 <c:ConverterParamHelper ConverterParam="{Binding ...}"> <c:ConverterParamHelper.Converter> <c:RealConverter/> </c:ConverterParamHelper.Converter> </c:ConverterParamHelper> 

我知道这是一个古老的问题,但也许这会对遇到它的人有用。 我find的解决scheme如下:

 public class WattHoursConverter : FrameworkElement, IValueConverter { #region Unit (DependencyProperty) /// <summary> /// A description of the property. /// </summary> public string Unit { get { return (string)GetValue(UnitProperty); } set { SetValue(UnitProperty, value); } } public static readonly DependencyProperty UnitProperty = DependencyProperty.Register("Unit", typeof(string), typeof(WattHoursConverter), new PropertyMetadata("", new PropertyChangedCallback(OnUnitChanged))); private static void OnUnitChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((WattHoursConverter)d).OnUnitChanged(e); } protected virtual void OnUnitChanged(DependencyPropertyChangedEventArgs e) { } #endregion public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { // you can use the dependency property here ... } } 

并在你的xaml:

 <UserControl.Resources> <converters:WattHoursConverter x:Key="WattHoursConverter" Unit="{Binding UnitPropFromDataContext}"/> </UserControl.Resources> .... <TextBlock Grid.Column="1" TextWrapping="Wrap" Text="{Binding TotalCO2, Converter={StaticResource KgToTonnesConverter}}" FontSize="13.333" />