简体   繁体   English

绑定按钮IsEnabled取决于组合框选择

[英]Binding Button IsEnabled depending of the ComboBox selection

I'm sure this is really easy, but I don't know how do it. 我敢肯定这确实很容易,但是我不知道该怎么做。 I have a ComboBox and a Button, and I need to have the Button enabled only if the ComboBox has an item selected, ie if in the ComboBox has no elements showing, then the Button must be disabled. 我有一个ComboBox和一个Button,仅当ComboBox选中了一个项目时才需要启用Button,即,如果ComboBox中没有显示任何元素,则必须禁用Button。 How can I do this? 我怎样才能做到这一点?

I have tried doing the following: 我尝试执行以下操作:

IsEnabled="{Binding ElementName=mycombobox, Path=SelectedIndex}"/>

But it does not work. 但这行不通。 I'm using Silverlight 5. 我正在使用Silverlight 5。

Thanks in advance 提前致谢

可能有一种更有效的方法,但我只需要确定SelectedIndexChanged事件中ComboBox.SelectedItem是否为null。

MSDN has something that may be of help to you here . MSDN 在这里可能会对您有所帮助。 It suggests you use a converter or a data trigger. 建议您使用转换器或数据触发器。 I haven't tested this, but perhaps this will work? 我还没有测试过,但是也许行得通吗?

<Window.Resources>
    <Style x:Key="MyButtonStyle" TargetType="{x:Type Button}">
        <Setter Property="IsEnabled" Value="True"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=SelectedItem, ElementName=comboBox1}" Value="{x:Null}">
                <Setter Property="UIElement.IsEnabled" Value="False"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

<Grid>
    <ComboBox Name="comboBox1">
        <ComboBoxItem>One</ComboBoxItem>
        <ComboBoxItem>Two</ComboBoxItem>
        <ComboBoxItem>Three</ComboBoxItem>
    </ComboBox>

    <Button Style="{StaticResource MyButtonStyle}" Name="myButton" Content="Push me"/>
</Grid>

EDIT 编辑

I am under the impression that Cyndy has already figured all this out, but for any future readers... 我的印象是Cyndy已经解决了所有这些问题,但是对于任何未来的读者来说……

As noted in the comments, you cannot do DataTriggers in Silverlight. 如评论中所述,您不能在Silverlight中执行DataTriggers。 You'll need to do a converter. 您需要做一个转换器。 Here is another post that may help. 是另一篇可能有所帮助的文章。 In essence, you'll need to have your XAML set something like: 本质上,您需要将XAML设置为:

<Button Content="MyButton" IsEnabled="{Binding SelectedItem, ElementName=comboBox1, Converter={StaticResource myConverter}}"/>

and then in your code-behind, you'll need something like: 然后在代码隐藏中,您将需要以下内容:

public class MyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return !(value == null);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM