我试图解决我无法指定动态值的事实ConverterParameter
. 请参阅我的其他问题,了解为什么我需要将动态值绑定到ConverterParameter- 我不喜欢当前发布的解决方案,因为它们都需要我认为对我的视图模型进行不必要的更改。
为了尝试解决这个问题,我创建了一个自定义转换器,并公开了该转换器的依赖属性:
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;
}
}
有没有办法在我的 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>
<!- ... ->
到目前为止我看到的示例仅绑定到静态资源。
Edit:
我收到一些反馈,表明只有一个带有我发布的 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>
<!- ... ->
因此,共享转换器的实例并不能解决这个问题:)