DataContext作为资源中转换器绑定的源

时间:2010-06-07 14:39:02

标签: wpf binding datacontext controltemplate ivalueconverter

             

 <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的绑定 在ControlTemplate的Root Visuals中重新计算?

4 个答案:

答案 0 :(得分:9)

以前的回答非常接近。但是多绑定内部的绑定应该是:

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

对我有用

答案 1 :(得分: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);

答案 2 :(得分:1)

这是一种简单有效的方法(适用于我的应用):

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

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

答案 3 :(得分:0)

for value in df[coluna].values:
       with open(r"path\f2.csv", 'a',encoding="utf8") as filew:
           filew.write(tabela+','+coluna+','+str(value)+'\n') 

点表示您绑定到数据上下文