无法从WPF中的另一个元素绑定到ZIndex

时间:2017-08-15 03:52:34

标签: c# wpf xaml

我想在同一个.navbar { background-color: white; border: none; /*color: #0000;*/ color: #000; } .navbar ul li > a{ color: #f00; } 文件中绑定WPF中另一个元素的ZIndex,但它不起作用。

要绑定的元素。

.xaml

初始绑定的元素。

<Border 
    x:Name="BubbleTop" 
    CornerRadius="5" 
    Background="#EBF5EB" 
    Padding="8,6" 
    BorderBrush="LightGray" 
    BorderThickness="1" 
    Grid.ZIndex="3">
        <ContentPresenter />
</Border>

在转换器中,它被设置为根据Border元素的ZIndex更改Foreground颜色。

<TextBlock
    x:Name="statusText"
    Margin="..."
    Foreground="{Binding ElementName=BubbleTop, Path=Grid.ZIndex, Converter={StaticResource ToggleColorConverter}}"
    FontWeight="Bold"
    Text="..."/>

但它不起作用。任何提示?

2 个答案:

答案 0 :(得分:3)

您拥有的转换器可以正常工作,但绑定的Path错误。绑定到附加属性时,必须将路径放在parens中才能正确解析路径。

那就是说,我不认为转换器在这里真的很有意义。您可以使用样式来处理这样的简单切换。这允许您在XAML中保留更多的视图逻辑。

例如:

<TextBlock
    x:Name="statusText"
    Margin="..."
    FontWeight="Bold"
    Text="...">
  <TextBlock.Style>
    <p:Style TargetType="TextBlock">
      <Setter Property="Foreground" Value="Blue"/>
      <p:Style.Triggers>
        <DataTrigger Binding="{Binding ElementName=BubbleTop, Path=(Grid.ZIndex)}" Value="3">
          <Setter Property="Foreground" Value="Red"/>
        </DataTrigger>
      </p:Style.Triggers>
    </p:Style>
  </TextBlock.Style>
</TextBlock>

(注意:你可以省略p:元素的<Style/> XML命名空间。我只是因为当XML中有一个普通的<Style/>元素时,Stack Overflow代码格式化程序会混淆并且不会正确格式化XML。)

答案 1 :(得分:1)

在你的价值转换器中试试这个:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
  int z = (int)value;
  if (z == 3)
    return Brushes.Red;
  else
    return Brushes.Blue;
}