如何在静态资源上设置依赖项属性?
我试图解决这个事实,我无法为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>
<!- ... ->
所以这个问题不会被其共享转换器:)
不幸的是这”不是个实例t去工作 - 我以前走过这条路,事实证明ItemsControl中的所有Items共享相同的Converter。我认为这是由于XAML解析器的工作原理。
首先你可以在更高层次上资源字典指定的转换,并且设置x:Shared
到false
,其次,如果你想“的值设置为项目的的ItemsSource”为你注释你可以指定一个空的绑定( Value="{Binding}"
)。
感谢“x:共享”信息。至于绑定,当我执行'Value =“{Binding}”''时,我的依赖属性的setter似乎永远不会被调用。 – 2011-05-05 21:57:29
内部机制不使用依赖项属性的设置程序,它们仅用于代码隐藏访问。这就是为什么除了SetValue/GetValue调用之外,不应该在其中放置任何代码。 – 2011-05-05 22:08:57
你是对的关于setter没有被调用。如果我从'Value =“{Binding}”'改变为'Value =“{StaticResource someOtherResource}',那么getter会返回那个静态资源实例,但是setter永远不会被调用,但是当我回到'Value =”{ Binding}“',getter返回'null' – 2011-05-05 23:56:49
是的,我可以看到这是一个问题。但是我注意到,如果我将它设置为控件上的资源,那么每个控件都会得到一个实例。如果更有意义,我可以改变我的问题。 – 2011-05-05 20:40:22