C# 文本框内按钮的RelayCommand
我在一个文本框中有一个按钮。我想为我的按钮绑定命令。但当我点击按钮时它不起作用。 下面是App.xaml中的文本框模板:C# 文本框内按钮的RelayCommand,c#,wpf,C#,Wpf,我在一个文本框中有一个按钮。我想为我的按钮绑定命令。但当我点击按钮时它不起作用。 下面是App.xaml中的文本框模板: <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <Scroll
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<ScrollViewer Name="PART_ContentHost"
VerticalAlignment="Center"
Margin="10,0" Grid.Column="0"/>
<Button Command="{Binding CmdRandom, RelativeSource={x:Static RelativeSource.Self}}"
Height="15"
Width="15"
Grid.Column="1" />
</Grid>
我的文本框:
<TextBox x:Name="txtName" Style="{StaticResource txtRnd}" MaxLength="63" Text="{Binding GetRnd, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" Grid.Row="1" />
如果要获取祖先的属性:
{Binding DataContext.CmdRandom, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type TextBox}}}
更多信息:
Binding RelativeSource={
RelativeSource Mode=FindAncestor, AncestorType={x:Type ItemType}}
RelativeSource
的默认属性是Mode
属性。此处提供了一组完整的有效值():
- PreviousData允许您在显示的数据项列表中绑定上一个数据项(而不是包含该数据项的控件)
- TemplatedParent是指应用了模板(数据绑定元素存在于其中)的元素。这类似于设置TemplateBindingExtension,仅当绑定位于模板内时才适用
- Self指的是要在其上设置绑定的元素,它允许您将该元素的一个属性绑定到同一元素上的另一个属性
- FindAncestor是指数据绑定元素父链中的祖先。您可以使用它绑定到特定类型或其子类的祖先。如果要指定AncestorType和/或AncestorLevel,请使用此模式
Binding RelativeSource={
RelativeSource Mode=FindAncestor, AncestorType={x:Type ItemType}}