我遇到了一个关于找到子元素的问题。我想访问Label中的TextBlock元素。但我找不到它。
这是我的MainWindow.xaml代码:
<Label x:Name="text" Style="{DynamicResource labelstyle}">
<TextBlock>asdasdasd</TextBlock>
</Label>
这是我的样式代码:
<Style x:Key="labelstyle" TargetType="Label">
<Setter Property="HorizontalContentAlignment" Value="Left" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Label">
<Border BorderThickness="2" BorderBrush="Red">
<TextBox x:Name="textBox" Text="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type TextBlock},
AncestorLevel=2},Path=Text}">
</TextBox>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我想将TextBox的Text属性绑定到TextBlock的Text属性中的Label。我该怎么办 ? 我希望我清楚自己。 谢谢。
答案 0 :(得分:0)
这将允许您通过绑定显示文本,用户可以选择它,但不能在TextBox中键入。如果您还想输入TextBox,请删除IsReadOnly="True"
<Label Height="30" Width="150">
<Label.Template>
<ControlTemplate TargetType="{x:Type Label}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Grid.Column="0"
MinWidth="26"
Margin="2"
Source="{Binding myImageSource}"/>
<TextBox Grid.Column="1"
IsReadOnly="True"
Text="{Binding myTextValue}"
Margin="5,2"/>
</Grid>
</ControlTemplate>
</Label.Template>
</Label>
答案 1 :(得分:0)
不要在标签中使用TextBlock,只需将其保留在模板中,并让它引用标签内容以显示文本。
以下是一个例子:
<Label x:Name="text" Content="asdasdasd" Style="{StaticResource labelstyle}"/>
和样式/模板
<Style x:Key="labelstyle" TargetType="{x:Type Label}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Label}">
<Border BorderThickness="2" BorderBrush="Red">
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{TemplateBinding Content}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style>
这应该为您提供您似乎想要实现的红色边框中的居中文本。
希望这对你有所帮助。