【问题标题】:How to set a nullable property value by Style setter?如何通过 Style setter 设置可为空的属性值?
【发布时间】:2015-09-17 14:08:25
【问题描述】:

我正在开发一个 Windows 应用商店 (8.1) 应用程序。

我有这个控件,它有一个可以为空的 int 属性(类型“int?”),当我尝试通过 Style 将它设置为 int 时,我得到一个错误。

<Setter Property="Minimum" Value="0" />

Error Cannot assign to nullable type on property Minimum

有什么想法吗?

【问题讨论】:

    标签: c# .net wpf windows-store-apps winrt-xaml


    【解决方案1】:

    以下示例描述了解决方案,根据您的需求进行调整。

    C#:

    class IsNullToBoolConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                return value == null;
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }
    

    XAML:

     <Window.Resources>
            <local:IsNullToBoolConverter x:Key="IsNullToBoolConverter"/>
     </Window.Resources>
    
        <TextBlock Text="Text">
            <TextBlock.Style>
                <Style TargetType="TextBlock">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Age, Converter={StaticResource IsNullToBoolConverter}}" Value="False">
                            <Setter Property="FontSize" Value="55"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBlock.Style>
        </TextBlock>
    

    【讨论】:

    • WinRT 不支持 DataTriggers。
    • Interaction & Interactivitiy 命名空间提供 DataTrigger。
    • 没错,但您的解决方案似乎不正确,这是在资源字典中,我没有将值绑定到任何东西。上次我尝试在 setter 中使用绑定时,失败得很惨(当然,为什么不呢?听起来很有用)
    【解决方案2】:

    您可以通过使用 TargetNullValue 属性来实现此目的。使用下面的代码,

    TargetNullValue={x:Static sys:String.Empty}
    

    注意:

    sys是mscorlib中System的导入xml命名空间:

    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    

    希望这会有所帮助..

    【讨论】:

    • x:Static 不适用于 WindowsStore 应用程序。 OP 正在开发 Windows 应用商店应用程序。
    猜你喜欢
    • 2023-01-20
    • 2016-04-04
    • 1970-01-01
    • 2011-01-19
    • 2011-04-19
    • 1970-01-01
    • 2023-03-13
    • 2016-04-11
    • 1970-01-01
    相关资源
    最近更新 更多