如何在TextBox.Template中获取Parent的DataContext?

时间:2017-11-21 10:05:40

标签: c# wpf

Label.BindingTextBox.Template确实可行,但当我想将ViewModel.Value绑定到TextBox内的TextBox.Template时,我总是得到

  

错误:40:BindingExpression路径错误:'object'上找不到'ViewModel'属性

有没有办法将DataContextTextBox.Template设置为DataContext中的Parent

<Style TargetType="{x:Type fields:CustomDateFieldView}">
     <Label Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ViewModel.Label}"/>
     <Setter Property="Template">
         <Setter.Value>
             <ControlTemplate TargetType="{x:Type fields:CustomDateFieldView}">
              ....
                <TextBox.Template>
                     <ControlTemplate> 
                         <StackPanel Orientation="Horizontal">
                         <TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ViewModel.Value}"/>
                          ....
                         </Stackpanel>
                    </ControlTemplate>
                </TextBox.Template>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

1 个答案:

答案 0 :(得分:0)

<Style TargetType="{x:Type fields:CustomDateFieldView}">
        <Label Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ViewModel.Label}"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type fields:CustomDateFieldView}">
                                  ....
                   <TextBox.Template>
                        <ControlTemplate> 
                        <StackPanel Orientation="Horizontal">
                        <TextBox Text="{Binding ViewModel.Value, ElementName = myControlName}"/>
                           ....
                        </Stackpanel>
                   </TextBox.Template>

如果为CustomDateFieldView控件指定x:Name,则可以使用此方法。在我的例子中,我把ElementName myControlName。这要求myControlName.DataContext当然是你的viewmodel

编辑:如果第一种方法不起作用,你可以试试这个:

<Style TargetType="{x:Type fields:CustomDateFieldView}">
            <Label Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ViewModel.Label}"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type fields:CustomDateFieldView}">
                                      ....
                       <TextBox.Template>
                            <ControlTemplate> 
                            <StackPanel Orientation="Horizontal">
                            <TextBox Text="{Binding ViewModel.Value, RelativeSource={RelativeSource AncestorType={x:Type fields:CustomDateFieldView}}}"/>
                               ....
                            </Stackpanel>
                       </TextBox.Template>