【问题标题】:Using a Style Trigger to change another control使用样式触发器更改另一个控件
【发布时间】:2017-12-04 13:11:59
【问题描述】:

我在一个窗口上有一个列表框和一个按钮。当 ListBox 获得焦点时,Button 的 IsEnabled 属性应为 True。这是我尝试过的:

<Style TargetType="{x:Type ListBox}">
    <Setter
        Property="Margin"
        Value="15,0,15,20"></Setter>
        <Style.Triggers>
            <Trigger Property="IsFocused" Value="True" />
            <Setter TargetName="btnActivate" Property="IsEnabled" Value="True" />
        </Style.Triggers>
</Style>

这看起来很简单,但我收到一条错误消息

btnActivate 无法识别。

这样做的正确方法是什么?

编辑 1 我实现了 MoonMoo 的建议链接如下:

IsEnabled="{Binding ElementName=lstInactive, Path=SelectedIndex, Converter={StaticResource cvtr}}">

使用此转换器:

Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
        Dim IsFocused As Integer = CInt(value)
        Return If(IsFocused > -1, True, False)
    End Function

这可以在列表框获得焦点时打开 IsEnabled,但在列表框失去焦点时不会关闭它。我想也许我必须研究一个多重绑定,它也绑定到可能获得焦点的其他控件。

编辑 2 我应该提到我尝试过:

IsEnabled="{Binding ElementName=lstInactive, Path=IsFocused, Converter={StaticResource cvtr}}">

使用转换器:

Return CBool(value)

但这并没有改变按钮的 IsEnabled 属性

【问题讨论】:

标签: wpf xaml triggers


【解决方案1】:

您可以使用DataTrigger 作为您的按钮:

<Button> 
   <Button.Style>
     <Style TargetType="Button">
        <Setter Property="IsEnabled" Value="False"/>
     <Style.Triggers>
        <DataTrigger Binding="{Binding IsFocused,ElementName=YourListBoxName}" Value="True">
           <Setter Property="IsEnabled" Value="True"/>
         </DataTrigger>
     </Style.Triggers>
    </Style>
   </Button.Style>
</Button>

【讨论】:

  • 这非常接近但不起作用。使用 IsFocused 时,按钮的 IsEnabled 属性不会更改。所以我尝试了 Focused (这是 ListBox 文档中命名的属性,但得到了一个运行时错误,即该属性“未找到”。另外,请参阅下一条评论。
  • 所以我尝试了所有其他有意义的 ListBox 属性,并得到了一个部分工作。我尝试了值为 0 的 SelectedIndex,当我单击 ListBox 中的第一项时,它起作用了。所以我通过使用 "> -1" 的值尝试了明显的下一步,它没有给出运行时错误,但也没有更改按钮的 IsEnabled 属性。
  • 所以你想要一些东西,如果任何项目被选中,按钮应该被启用?
  • 不,不完全是。如果列表框具有焦点,我希望启用它。我只是尝试使用 SelectedIndex 作为测试各种方法的一种方式,看看我是否能得到我想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 2012-04-22
  • 2012-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多