wpf 绑定到元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6803392/
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 23:00:09  来源:igfitidea点击:

wpf binding to element

wpfxamldata-binding

提问by kaycee

Well i guess it's easy my scenario is having 2 elements: ListBoxand Button:

好吧,我想我的场景很容易有 2 个元素: ListBoxButton

<ListBox Name="BannedItemsListBox"
         Margin="5"
         MinWidth="100"
         MaxWidth="100" " Height="
         204" ItemsSource="{Binding Path=BannedItems, Mode=TwoWay}"></ListBox>
<Button Name="RemoveBannedItemsButton"
        Margin="5"
        MinWidth="65"
        Height="22"
        Click="RemoveBannedItemButton_Click">Remove</Button>

I want to bind the IsEnabledproperty button to be true only if Item from ListBox is selected (focused) in XAML

IsEnabled仅当在XAML 中选择(聚焦)来自 ListBox 的项目时,我才想将属性按钮绑定为 true

I tried

我试过

IsEnabled="{Binding ElementName=BannedSourcesListBox, Path=TouchesDirectlyOver.Count}"

but no go.

但不行。

回答by H.B.

What does the selection have to do with the Touches? (Also the ElementNameis off)

选择与 Touches 有什么关系?(也ElementName关了)

I would try this:

我会试试这个:

IsEnabled="{Binding SelectedItems.Count, ElementName=BannedItemsListBox}"

Edit:Apparently, unlike the trigger-variant, people do not seem to see how this works: Basically the binding system tries to convert the input to the property at hand, a boolean, so when it gets an integer, 0will be converter to false, anything higher to true. So the Button will be enabled if one or more items are selected.

编辑:显然,与触发器变体不同,人们似乎没有看到它是如何工作的:基本上绑定系统试图将输入转换为手头的属性,一个布尔值,所以当它得到一个整数时,0将转换为false,任何更高的true。因此,如果选择了一项或多项,则 Button 将被启用。

回答by sternr

<Button Content="Button"
        Height="23"
        HorizontalAlignment="Left"
        Margin="138,12,0,0"
        Name="button1"
        VerticalAlignment="Top"
        Width="75"
        Click="button1_Click">
    <Button.Style>
        <Style>
            <Setter Property="Button.IsEnabled"
                    Value="True" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=lstTest , Path=SelectedItem}"
                             Value="{x:Null}">
                    <Setter Property="Button.IsEnabled"
                            Value="False" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>