1

通常我将标签与文本框/组合框一对一地关联起来,这样我就可以在组合框有焦点时装饰标签......像这样

<Label
    Grid.Row="1"
    Grid.Column="1"
    Style="{StaticResource styleLabelTextBlockLeft}"
    Tag="{Binding ElementName=cboColor, Path=(IsFocused)}"
>
    <TextBlock
        TextWrapping="Wrap">What is your favorite color? 
    </TextBlock>
</Label>
<ComboBox
    x:Name="cboColor"
    Grid.Row="1"
    Grid.Column="3"
    ...
/>

如果标签右侧的 ComboBox 具有焦点或第一个 ComboBox 右侧的第二个 ComboBox 具有焦点(都在同一行),我想做的是突出显示标签。伪代码如下:

<Label
    Grid.Row="1"
    Grid.Column="1"
    Style="{StaticResource styleLabelTextBlockLeft}"
    Tag="{Binding ElementName=cboColorOne, Path=(IsFocused)}"
    Tag="{Binding ElementName=cboColorTwo, Path=(IsFocused)}"
>
    <TextBlock
        TextWrapping="Wrap">What is your favorite color? 
    </TextBlock>
</Label>
<ComboBox
    x:Name="cboColorOne"
    Grid.Row="1"
    Grid.Column="3"
    ...
/>
<ComboBox
    x:Name="cboColorTwo"
    Grid.Row="1"
    Grid.Column="5"
    ...
/>

有任何想法吗?谢谢。

4

3 回答 3

2

如果您想要一个纯 xaml 解决方案,您可以使用样式数据触发器。在样式中将标签默认为 false,然后为每个组合框编写一个触发器,当聚焦时将标签设置为 true。

<Label.Style>
   <Style TargetType="Label" BasedOn="{StaticResource styleLabelTextBlockLeft}">
     <Setter Property="Tag" Value="False" />
     <Style.Triggers>
       <DataTrigger Binding="{Binding ElementName=cboColor, Path=(IsFocused)}" Value="True">
         <Setter Property="Tag" Value="True" />
       </DataTrigger>
       <DataTrigger Binding="{Binding ElementName=cboColor2, Path=(IsFocused)}" Value="True">
         <Setter Property="Tag" Value="True" />
       </DataTrigger>
 </Style.Triggers>
   </Style>

于 2012-06-21T22:25:47.110 回答
1

您可以使用 MultiBinding/MultiValueConverter。只需从 IMultiValeConverter 派生一个类,如下所示:

public class ComboBoxFocusedConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return (bool)values[0] || (bool)values[1];
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        return new object[0]
    }
}

然后在您的资源中引用它:

<....Resources>
    <yournamespace:ComboBoxFocusedConverter x:Key="ComboBoxFocusedConverter" />
</....Resources>

并像这样使用它:

<Label
    Grid.Row="1"
     Grid.Column="1"
    Style="{StaticResource styleLabelTextBlockLeft}"
>
    <Label.Tag>
        <MultiBinding Converter="{StaticResource ComboBoxFocusedConverter}">
            <Binding ElementName="cboColorOne" Path="IsFocused" />
            <Binding ElementName="cboColorTwo" Path="IsFocused" />
        </MultiBinding>
    </Label.Tag>
    <TextBlock
        TextWrapping="Wrap">What is your favorite color? 
    </TextBlock>
</Label>
于 2012-06-21T22:23:56.997 回答
1

您可以编写一个具有实现所需逻辑的属性的类,然后将包含相关标签的控件的 DataContext 绑定到该类。接下来,将此标签的标签绑定到类的属性。

于 2012-06-21T22:11:05.500 回答