简体   繁体   中英

How to set a nullable property value by Style setter?

I am developing a Windows Store (8.1) application.

I have this control which has a nullable int property (type "int?"), when I try to set it to an int via Style, I get an error.

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

Error Cannot assign to nullable type on property Minimum

Any ideas?

Following sample depicts solution, adjust it to your demands.

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>

you can achieve this by using TargetNullValue property. Use below code,

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

Note :

sys is the imported xml namespace for System in mscorlib:

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

Hope this will help..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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