![](/img/trans.png)
[英]How to bind ColorBrush from inside ControlTemplate to a custom property outside of ControlTemplate?
[英]How can I bind this Textblock inside ControlTemplate in button style?
我有一個Button
樣式,這個樣式包含一個圖標和一個文本。 我想綁定文本。 我怎樣才能做到這一點?
<Style TargetType="{x:Type Button}" x:Key="ConnectedButton">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="FlowDirection" Value="LeftToRight"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Padding="5 0"
Width="80"
Height="30"
Margin="5">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock Text="{Binding Connect}"
Margin="3 0" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBlock Text="{StaticResource ConnectIcon}"
Style="{StaticResource Icon_Text}" Margin="3 0"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
使用MainWindow.xaml
中的樣式:
<Button Style="{StaticResource ConnectedButton}" Margin="10,15,0,10" x:Name="cnct_btn" Content="{StaticResource Connect}" Height="40" Width="80 " HorizontalAlignment="Left" VerticalAlignment="Center" Click="Cnct_Click"/>
MainWindow.xaml.cs
bool test = false;
//...
if (test)
{
cnct_btn.Content = "Connect";
}
else
{
cnct_btn.Content = "Not Connected";
}
我試過Text={Binding Connect}
但它不起作用。
在控件模板中,您必須使用TemplateBinding
來訪問模板化控件上的屬性。 如果是Button
,它是您要綁定的Content
屬性。
實現一個標記擴展,該擴展支持模板中的屬性值與模板化控件上的某些其他公開屬性的值之間的綁定。
<TextBlock Text="{TemplateBinding Content}"
Margin="3 0" HorizontalAlignment="Center" VerticalAlignment="Center"/>
一個簡單的Binding
將解析當前數據上下文的屬性。 您也可以完成這項工作,但您需要使用TemplatedParent
指定RelativeSource
。
TemplatedParent
- 指應用模板(數據綁定元素所在的元素)的元素。 這與設置TemplateBindingExtension
類似,並且僅適用於 Binding 在模板內的情況。
<TextBlock Text="{Binding Content, RelativeSource={RelativeSource TemplatedParent}}"
Margin="3 0" HorizontalAlignment="Center" VerticalAlignment="Center"/>
請注意,在這種情況下,一個TemplateBinding
就足夠了, 因為它只是一種方式。 在雙向綁定中,您必須使用使用RelativeSource
和TemplatedParent
的變體。
TemplateBinding
是針對模板場景的Binding
優化形式,類似於使用{Binding RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}
構造的 Binding。TemplateBinding
始終是單向綁定,即使涉及的屬性默認為雙向綁定。 涉及的兩個屬性都必須是依賴屬性。 為了實現與模板化父級的雙向綁定,請改用以下綁定語句{Binding RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay, Path=MyDependencyProperty}
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.