我想同步两个TextBlockes的背景。例如,如果鼠标位于任何文本块之上,我想将两种文本块的背景颜色更改为相同。我知道我可以使用此触发器来更改一个背景:
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Background" Value="LightGray"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Gray"/>
</Trigger>
</Style.Triggers>
</Style>
但是如何同步呢?
更新:这不起作用:
<UserControl.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Background" Value="LightGray"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Gray"/>
</Trigger>
</Style.Triggers>
</Style>
</UserControl.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Background="{Binding Path=Background, ElementName=tbHeader, Mode=TwoWay}" Text="A"/>
<TextBlock x:Name="tbHeader" Grid.Column="1" Text="B"/>
</Grid>
答案 0 :(得分:0)
<TextBlock x:Name=textBlock1>
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Background" Value="LightGray"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Gray"/>
</Trigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
<TextBlock Background={Binding Path=Background ElementName=textBlock1/><!--Background gets set from textBlock1-->
答案 1 :(得分:0)
您可以将它们置于ContentControl
并在此ControlTemplate
上应用触发器来同步它 -
<Grid>
<ContentControl>
<ContentControl.Template>
<ControlTemplate>
<StackPanel>
<TextBlock Text="Rohit" x:Name="txt1"/>
<TextBlock Text="Vats" x:Name="txt2"/>
</StackPanel>
<ControlTemplate.Triggers>
<Trigger Property="TextBlock.IsMouseOver" SourceName="txt1"
Value="True">
<Setter Property="TextBlock.Background" Value="Red"
TargetName="txt1"/>
<Setter Property="TextBlock.Background" Value="Red"
TargetName="txt2"/>
</Trigger>
<Trigger Property="TextBlock.IsMouseOver" SourceName="txt2"
Value="True">
<Setter Property="TextBlock.Background" Value="Red"
TargetName="txt1"/>
<Setter Property="TextBlock.Background" Value="Red"
TargetName="txt2"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ContentControl.Template>
</ContentControl>
</Grid>
答案 2 :(得分:0)
如果您正在寻找'正确'的MVVM方式,您应该将鼠标悬停事件/属性绑定到视图模型的相同属性,并将背景绑定到同一属性,并使用转换器将其转换为适当的颜色(或带模板的样式)。