我试图解决这个事实,我无法为ConverterParameter
指定动态值。 See my other question for why I need to bind a dynamic value to ConverterParameter
- 我不喜欢目前发布的解决方案,因为它们都需要我觉得应该对View Model进行不必要的更改。如何在静态资源上设置依赖项属性?
要尝试解决这个问题,我创建了一个自定义转换器,并在该转换器暴露一个依赖属性:
public class InstanceToBooleanConverter : DependencyObject, IValueConverter
{
public object Value
{
get { return (object)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(object), typeof(InstanceToBooleanConverter), null);
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value != null && value.Equals(Value);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.Equals(true) ? Value : Binding.DoNothing;
}
}
有没有办法使用绑定(或样式setter方法来设置这个值,或其他疯狂的方法)在我的XAML?
<ItemsControl ItemsSource="{Binding Properties}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type local:SomeClass}">
<DataTemplate.Resources>
<!-- I'd like to set Value to the item from ItemsSource -->
<local:InstanceToBooleanConverter x:Key="converter" Value="{Binding Path=???}" />
</DataTemplate.Resources>
<!- ... ->
到目前为止我见过的例子只绑定到静态资源。
编辑:
我得到了一些反馈意见,只有一个与我张贴的XAML转换器实例。
我可以解决此通过将资源在我的控制:
<ItemsControl ItemsSource="{Binding Properties}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type local:SomeClass}">
<RadioButton Content="{Binding Name}" GroupName="Properties">
<RadioButton.Resources>
<!-- I'd like to set Value to the item from ItemsSource -->
<local:InstanceToBooleanConverter x:Key="converter"
Value="{Binding Path=???}" />
</RadioButton.Resources>
<RadioButton.IsChecked>
<Binding Path="DataContext.SelectedItem"
RelativeSource="{RelativeSource AncestorType={x:Type Window}}"
Converter="{StaticResource converter}" />
</RadioButton.IsChecked>
</RadioButton>
<!- ... ->
所以这个问题不会被其共享转换器:)
是的,我可以看到这是一个问题。但是我注意到,如果我将它设置为控件上的资源,那么每个控件都会得到一个实例。如果更有意义,我可以改变我的问题。 – 2011-05-05 20:40:22