如何在静态资源上设置依赖项属性?

时间:2011-05-05 19:59:49

标签: wpf data-binding mvvm ivalueconverter staticresource

我正试图绕过这样一个事实:我无法为ConverterParameter指定动态值。 See my other question for why I need to bind a dynamic value to ConverterParameter - 我不喜欢目前发布的解决方案,因为它们都需要我认为应该对我的View模型进行不必要的更改。

为了尝试解决这个问题,我创建了一个自定义转换器,并在该转换器上公开了依赖项属性:

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只有一个转换器实例。

我可以通过将资源放在我的控制中来解决这个问题:

<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>
<!- ... ->

因此,必须共享转换器的实例才能阻止此问题:)

2 个答案:

答案 0 :(得分:1)

不幸的是,这不会起作用 - 我之前一直在这条路上,事实证明ItemsControl中的所有项目共享相同的转换器。我认为这是由于XAML解析器的工作方式。

答案 1 :(得分:0)

首先,您可以在更高级别的资源字典中指定转换器,并将x:Shared设置为false,其次,如果您要“将值设置为ItemsSource中的项目 “在您注释时,您只需指定一个空绑定(Value="{Binding}")。