根据 ListBox.SelectedIndex 在 WPF 中启用按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 19:35:17  来源:igfitidea点击:

Enabling a button in WPF depending on ListBox.SelectedIndex

wpflistbox

提问by Rune Jacobsen

I have a rather classic UI situation - two ListBoxes named SelectedItemsand AvailableItems- the idea being that the items you have already selected live in SelectedItems, while the items that are available for adding to SelectedItems(i.e. every item that isn't already in there) live in AvailableItems.

我有一个相当经典的 UI 情况 - 两个 ListBoxes 命名SelectedItemsAvailableItems- 想法是您已经选择SelectedItems的项目SelectedItems位于AvailableItems.

Also, I have the <and >buttons to move the current selection from one list to the other (in addition to double clicking, which works fine).

另外,我有<>按钮可以将当前选择从一个列表移动到另一个列表(除了双击,这很好用)。

Is it possible in WPF to set up a style/trigger to enable or disable the move buttons depending on anything being selected in either ListBox? SelectedItemsis on the left side, so the <button will move the selected AvailableItemsto that list. However, if no items are selected (AvailableItems.SelectedIndex == -1), I want this button to be disabled (IsEnabled == false) - and the other way around for the other list/button.

是否可以在 WPF 中设置样式/触发器以根据在任一列表框中选择的任何内容启用或禁用移动按钮?SelectedItems位于左侧,因此该<按钮会将所选内容移动AvailableItems到该列表中。但是,如果未选择任何项目 ( AvailableItems.SelectedIndex == -1),我希望禁用此按钮 ( IsEnabled == false) - 以及其他列表/按钮的其他方式。

Is this possible to do directly in XAML, or do I need to create complex logic in the codebehind to handle it?

这是否可以直接在 XAML 中完成,或者我是否需要在代码隐藏中创建复杂的逻辑来处理它?

回答by Karlas

Less code solution:

少代码解决方案:

<Button Name="button1" IsEnabled="{Binding ElementName=listBox1, Path=SelectedItems.Count}" />

If count is 0 that seems to map to false, > 0 to true.

如果 count 是 0 似乎映射到 false,> 0 映射到 true。

回答by Karlas

Here's your solution.

这是您的解决方案。

<Button Name="btn1" >click me    
    <Button.Style>        
        <Style>            
            <Style.Triggers>                
                <DataTrigger 
                     Binding ="{Binding ElementName=list1, Path=SelectedIndex}" 
                     Value="-1">                    
                    <Setter Property="Button.IsEnabled" Value="false"/>                    
                </DataTrigger>                
            </Style.Triggers>            
        </Style>        
    </Button.Style>    
</Button>