2010-06-07 97 views
5

的DataContext作为源动力转换器绑定内的资源

<Canvas.DataContext> 
    <ViewModels:VMSomeControl Model="{Binding RelativeSource={RelativeSource TemplatedParent}}" /> 
</Canvas.DataContext> 

<!-- DataContext is not passed into these Instances. 
     they also have no knowledge of their TemplatedParent. --> 
<Canvas.Resources> 

    <!-- is there a way to use a binding that points to the datacontext within the resources ? --> 
    <Converters:SomeConverter x:Key="someConverter" 
          SomeProperty="{Binding Path=Model.SomeProperty}" /> 

    <!-- is there a way to point Directly to the TemplatedParent ? --> 
    <Converters:SomeConverter x:Key="someConverter" 
          SomeProperty="{TemplateBinding SomeProperty}" /> 

</Canvas.Resources> 


<SomeFrameworkElement SomeProperty="{Binding Path=Model.SomeOtherProperty, Converter={StaticResource someConverter}, ConverterParameter=0}" /> 

<SomeFrameworkElement SomeProperty="{Binding Path=Model.SomeOtherProperty, Converter={StaticResource someConverter}, ConverterParameter=1}" /> 

</Canvas> 

是否有可能使用请使用在DataContext或TemplatedParent 在一个控件模板的根视觉效果resourecs绑定?

+0

由于某种原因,stackoverflow截断了我的样式和控件模板。 此Canvas位于控件模板的根部。 – 2010-06-07 14:42:46

回答

6

如果你想你的价值转换器能够访问DataContext的,你可能需要使用ConverterParameter代替:

<SomeFrameworkElement SomeProperty="{Binding Path=Model.SomeOtherProperty, Converter={StaticResource someConverter}, ConverterParameter={Binding DataContext}}" /> 

在DataContext将被传递到你的价值转换器作为参数传递给您的实现的 IValueConverter.Convert


您可以成为可绑定的参数,如果实现IMultiValueConverter并使用XAML的MultiBinding类绑定的参数传递给您的valueconverter:

<SomeFrameworkElement> 
    <SomeFrameworkElement.SomeProperty> 
     <MultiBinding Converter="{StaticResource someConverter}" > 
      <Binding Path="DataContext"/> 
     </MultiBinding>   
    </SomeFrameworkElement.SomeProperty> 
</SomeFrameworkElement> 

<MultiBinding>元素的绑定元素传递Convert方法IMultiValueConverter作为values参数。 Convert具有以下签名:

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture); 
+0

不幸的是,你不能在“ConverterParameter” 上使用绑定,尽管这样做确实很方便。 – 2010-06-07 15:10:56

+1

你当然是绝对正确的。但我认为你可以使用多重绑定。我相应地更新了我的答案。 – 2010-06-07 21:05:26

+0

我还没有机会测试这个,因为我一直在做其他一些项目。但如果能解决我的问题,我一定会给你信用的。 – 2010-06-10 18:26:07

9

上一个答案重新真的很接近。但multibinding里面的结合应该是:

<SomeFrameworkElement> 
    <SomeFrameworkElement.SomeProperty> 
     <MultiBinding Converter="{StaticResource someConverter}" > 
      <Binding /> 
     </MultiBinding>   
    </SomeFrameworkElement.SomeProperty> 
</SomeFrameworkElement> 

为我工作

+0

在我的情况下抛出一个异常“双向绑定需要Path或XPath。”。我绑定TextBox的Text属性。 – marbel82 2017-06-02 13:08:52

1

下面是一个简单而有效的方式(即我的应用程序的工作原理):

<DataGrid.Columns> 
    <DataGridTextColumn Width="*" Header="ColumnHeader"> 
     <DataGridTextColumn.Binding> 
      <Binding Converter="{StaticResource YourConverterKey}" ConverterParameter="DataContext"/> 
     </DataGridTextColumn.Binding> 
    </DataGridTextColumn> 

现在你可以使用(价值)Convertor方法作为您的DataContext