Label.Binding
外TextBox.Template
确实可行,但当我想将ViewModel.Value
绑定到TextBox
内的TextBox.Template
时,我总是得到
错误:40:BindingExpression路径错误:'object'上找不到'ViewModel'属性
有没有办法将DataContext
内TextBox.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>
答案 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>