[英]Change property of controls child object by using Styles or DataTemplate in WPF application
假設我有一個按鈕,並且里面有一個圖像(盡管它可以是任何控件):
<Button Width="150" Height="80">
<Image Source="..." Width="50" Height="50" />
</Button>
我想在鼠標懸停時更改按鈕的樣式並制作它,以便在它發生時我也可以更改內部圖像的屬性。
<Style TargetType="Button">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Opacity" Value="0.5" />
<!-- Here I want to change alignment of the image inside the button if there is one -->
<Setter Property="Image.HorizontalAlignment" Value="Right" />
</Trigger>
</Style.Triggers>
</Style>
但是這種方式不起作用,並且由於某種原因,任何子控件都開始更改 alignment,不僅是圖像,還有文本和其他控件。 我試過的其他東西沒有編譯。 可能應該使用 DataTemplate; 我是 WPF 和 XAML 的新手,我仍然不太了解它,也找不到我需要的東西。
您應該使用HorizontalContentAlignment
ntalContentAlignment 設置按鈕的內容 alignment:
<Setter Property="HorizontalContentAlignment" Value="Right" />
根據您在下面的評論,我可以舉一個例子:
<Button Grid.Row="2" Width="150" Height="80">
<DockPanel Height="80" Width="150"><!-- A more complex control here-->
<Image Width="50" Height="50">
<Image.Source>
<BitmapImage DecodePixelWidth="50" UriSource="https://www.gravatar.com/avatar/9eae4ae63d70142e81f0365de42474ae?s=32&d=identicon&r=PG&f=1" />
</Image.Source>
</Image>
</DockPanel>
<Button.Style>
<Style TargetType="Button">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Opacity" Value="0.5" />
</Trigger>
</Style.Triggers>
<Style.Resources>
<Style TargetType="Image"><!-- The style target to the image control only in the button control -->
<Style.Triggers>
<!-- Binding to IsMouseOver of the button-->
<DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource AncestorType={x:Type Button}}}" Value="True">
<Setter Property="HorizontalAlignment" Value="Right" />
</DataTrigger>
</Style.Triggers>
</Style>
</Style.Resources>
</Style>
</Button.Style>
</Button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.