に動的な値を指定できないという事実を回避しようとしています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>
<!- ... ->
これまで見てきた例は、静的リソースにバインドするだけです。
編集:
私が投稿した XAML にはコンバーター インスタンスが 1 つしかないというフィードバックがありました。
リソースを自分のコントロールに配置することで、これを回避できます。
<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>
<!- ... ->
したがって、コンバーターのインスタンスを共有する必要があるため、この問題はブロックされません:)