通过Tag将WPF标签绑定到多个ComboBox

时间:2012-06-21 21:59:52

标签: wpf xaml label

通常我会将标签与TextBoxes / ComboBoxes一对一关联,这样我可以在ComboBox有焦点时装饰标签......就像这样

<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"
    ...
/>

有什么想法吗?感谢。

3 个答案:

答案 0 :(得分: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>

答案 1 :(得分:1)

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

答案 2 :(得分: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>