c# - 如何在 Trigger 的 ListBoxItem 中找到子控件的 IsEnabled 属性

标签 c# wpf xaml triggers isenabled

我试图根据 ListBoxItem 内容的 IsEnabled 属性禁用 ListBox 项目。与此代码一样,按钮 1 具有 IsEnabled=False,但列表框项目是可选的。如果 contents IsEnabled 属性为 false,我想禁用选择。应如何触发对项目内容及其 IsEnabled 属性的搜索。

<Grid>
      <ListBox>
         <ListBox.ItemTemplate>
            <DataTemplate>
               <DataTemplate.Triggers>
                  <Trigger Property="IsEnabled"  Value="False">
                     <Setter Property="IsEnabled" Value="False"/>
                  </Trigger>
               </DataTemplate.Triggers>
            </DataTemplate>
         </ListBox.ItemTemplate>
         <ListBoxItem>
            <Button IsEnabled="False">1</Button>
         </ListBoxItem>
         <ListBoxItem>
            <Button>2</Button>
         </ListBoxItem>
         <ListBoxItem>
            <Button>3</Button>
         </ListBoxItem>         
      </ListBox>
</Grid>

最佳答案

为什么不直接在 ListBoxItem 上设置 IsEnabled 呢?它也应该禁用 Button

但是也就是说,您可以使用 RelativeSource 绑定(bind)将 Button.IsEnabled 绑定(bind)到 ListBoxItem.IsEnabled,并设置 ListBoxItem 的 IsEnabled 属性,Button 也是如此

<Button IsEnabled="{Binding IsEnabled, 
    RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}" />

如果您正在使用 WPF,我强烈建议您查看 MVVM 设计模式。它非常适合 WPF,使用它您可以将 ListBoxItem.IsEnabledButton.IsEnabled 绑定(bind)到 DataContext 中的同一属性/p>

关于c# - 如何在 Trigger 的 ListBoxItem 中找到子控件的 IsEnabled 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9801559/

相关文章:

c# - XAML 中的动画按钮背景颜色

c# - 构建后消失的用户控件

c# - Asp.Net Core MVC 中的自定义相对路径

c# - 按两列分组并使用元组作为键 C# Linq 执行 ToDictionary

c# - MVC3 - Ajax Action 链接 - OnBegin,onComplete

c# - 可选参数是否应该列在构造函数签名中?

c# - ContentControl 不显示内容

c# - 绑定(bind)到 WPF 中的另一个绑定(bind)

wpf - 从 Windows 7 WPF 访问 Live SDK Skydrive

c# - XAML UWP 单选按钮图标居中对齐