【问题标题】:Enable/Disable Combobox if label content changed如果标签内容更改,则启用/禁用组合框
【发布时间】:2017-12-12 08:26:32
【问题描述】:

如果标签在 xaml 中有内容,是否可以启用/禁用组合框? (我正在寻找 xaml 解决方案。)

<Label x:Name="lbl_AusgewählteEmail" HorizontalAlignment="Left"
    Margin="37,132,0,0" VerticalAlignment="Top" Width="607"
    Content="{Binding ElementName=combx_UnzustellbarMailAuswahl, Path=SelectedItem}"/>

<ComboBox x:Name="combx_Auswahl" HorizontalAlignment="Left" 
    Margin="37,219,0,0" VerticalAlignment="Top" Width="318"/>

【问题讨论】:

    标签: wpf xaml


    【解决方案1】:

    在纯 XAML 中,没有。但是,您可以使用 IValueConverter 将该字符串转换为布尔值:

    public class NonEmptyStringToBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is string)
                return !String.IsNullOrEmpty((string) value);
            return false;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }
    
    <Window.Resources>
        <yourNameSpace:NonEmptyStringToBooleanConverter x:Key="StringToBool"/>
    </Window.Resources>
    
    <Label x:Name="lbl_AusgewählteEmail" HorizontalAlignment="Left"
       Margin="37,132,0,0" VerticalAlignment="Top" Width="607"
       Content="{Binding ElementName=combx_UnzustellbarMailAuswahl, Path=SelectedItem}"/>
    
    <ComboBox x:Name="combx_Auswahl" HorizontalAlignment="Left" 
        Margin="37,219,0,0" VerticalAlignment="Top" Width="318"
        IsEnabled="{Binding ElementName=combx_UnzustellbarMailAuswahl, Path=SelectedItem, Converter={StaticResource StringToBool}"/>
    

    也可以通过Style 执行此操作,但老实说这有点奇怪。为了完整起见:

    在包含控件/窗口的顶部包含以下命名空间:

    xmlns:system="clr-namespace:System;assembly=mscorlib"
    
    <ComboBox.Style>
        <Style TargetType="ComboBox">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=combx_UnzustellbarMailAuswahl, Path=SelectedItem}" Value="{x:Static system:String.Empty}">
                    <Setter Property="IsEnabled" Value="False"></Setter>
                </DataTrigger>
                <DataTrigger Binding="{Binding ElementName=combx_UnzustellbarMailAuswahl, Path=SelectedItem}" Value="{x:Null}">
                    <Setter Property="IsEnabled" Value="False"></Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ComboBox.Style>
    

    【讨论】:

    • 我们可以检查{x:Null} string.Empty
    • 它的本地化。某些 DataType(如 DateTime)具有取决于所选文化的默认格式。
    • @Raizzen 你是否包含了system 命名空间? (以上样式示例)
    • @ManfredRadlwimmer 是的,但它已解决。我有一个“/”太多了..谢谢所有
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多