6

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

是否可以在 ControlTemplate 的根视觉资源中使用使用 dataContext 或 TemplatedParent 的绑定?

4

4 回答 4

11

以前的答案真的很接近。但多重绑定内的绑定应该是:

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

对我有用

于 2011-03-04T18:01:09.807 回答
6

如果您希望您的值转换器能够访问数据上下文,您可能需要使用 ConverterParameter:

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

然后,数据上下文将作为IValueConverter.Convert实现的参数传递给您的值转换器。


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

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

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

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture);
于 2010-06-07T15:03:04.730 回答
1
SomeProperty="{Binding . ,Converter={StaticResource SomeConverter}, ConverterParameter=someParam}"

点告诉您绑定到 datacontext

于 2021-06-16T22:43:14.777 回答
-2

Here is a simple and efficient way (that works for my app):

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

Now you can use (value) in the Convertor method as your DataContext.

于 2014-10-26T10:02:51.607 回答