簡體   English   中英

如何以按鈕樣式在 ControlTemplate 中綁定此 Textblock?

[英]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就足夠了, 因為它只是一種方式 在雙向綁定中,您必須使用使用RelativeSourceTemplatedParent的變體。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM