簡體   English   中英

wpf樣式setter中的TemplateBinding?

[英]TemplateBinding in wpf style setter?

我在我的wpf應用程序中使用<setter> ,我需要使用TemplateBinding為該setter屬性在編譯時評估該值,但我不能使用TemplateBinding,它拋出一個錯誤,

我的代碼在下面:

                <ControlTemplate TargetType="{x:Type srcview:ButtonView}">
                    <Button>
                        <Button.Style>
                            <Style TargetType="{x:Type Button}">
                                <Style.Triggers>
                                    <Trigger Property="IsMouseOver" Value="True">
                                        <Setter Property="Background" Value="{TemplateBinding Color}"></Setter>
                                    </Trigger>
                                </Style.Triggers>
                            </Style>
                        </Button.Style>
                    </Button>
                </ControlTemplate>

我如何在我的樣式設置器中使用TemplateBinding ,還是有其他方法在編譯時評估值?

確實,setter不支持TemplateBinding。 試試這個:

<Setter Property="Background"
        Value="{Binding Color, RelativeSource={RelativeSource Self}}"/>

但請注意,您所引用的顏色屬性必須是類型刷。 背景是畫筆,您無法將顏色綁定到畫筆。

如果您絕對使用TemplateBinding,則反轉您的觸發器正在播放的角色。 讓它根據IsMouseOver設置它的值為False,然后直接在按鈕上使用TemplateBinding。 這種方法的缺點是你必須在觸發器中提供靜態值。 例如。

<Window x:Class="StackOverflow._20799186.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ControlTemplate x:Key="ControlAsButtonTemplate" TargetType="{x:Type ContentControl}">
            <Button x:Name="MyButton" Content="Hello World!" Background="{TemplateBinding Background}" />

            <ControlTemplate.Triggers>
                <Trigger SourceName="MyButton" Property="IsMouseOver" Value="False">
                    <Setter TargetName="MyButton" Property="Background" Value="Silver" />
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </Window.Resources>

    <ContentControl Template="{StaticResource ControlAsButtonTemplate}" Background="Green" />
</Window>

注意ControlTemplate.Triggers的用戶而不是Button.Style.Triggers。

我希望這有幫助。

您可能需要在模板中定義Color屬性才能綁定到該屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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