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

Aar*_*old 5 wpf datacontext binding 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>
Run Code Online (Sandbox Code Playgroud)

是否可以使用在ControlTemplate的Root Visuals中使用dataContext或TemplatedParent的绑定?

Mar*_*oll 9

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

<SomeFrameworkElement>
    <SomeFrameworkElement.SomeProperty>
        <MultiBinding Converter="{StaticResource someConverter}" >
            <Binding />
        </MultiBinding>        
    </SomeFrameworkElement.SomeProperty>
</SomeFrameworkElement>
Run Code Online (Sandbox Code Playgroud)

这对我有用


Jak*_*sen 6

如果您希望您的值转换器能够访问datacontext,您可能需要使用ConverterParameter:

<SomeFrameworkElement SomeProperty="{Binding Path=Model.SomeOtherProperty, Converter={StaticResource someConverter}, ConverterParameter={Binding DataContext}}" />
Run Code Online (Sandbox Code Playgroud)

然后,datacontext将作为IValueConverter.Convert实现的参数传递给您的值转换器.


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

<SomeFrameworkElement>
    <SomeFrameworkElement.SomeProperty>
        <MultiBinding Converter="{StaticResource someConverter}" >
            <Binding Path="DataContext"/>
        </MultiBinding>        
    </SomeFrameworkElement.SomeProperty>
</SomeFrameworkElement>
Run Code Online (Sandbox Code Playgroud)

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

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture);
Run Code Online (Sandbox Code Playgroud)