使用默认值的WPF绑定

时间:2018-06-15 09:07:39

标签: c# wpf xaml data-binding binding

我正在使用Binding定义三种不同颜色来填充ellipse

为了在我的绑定中执行此操作,我使用了包含converter

Enum

根据返回的enum,填充颜色已更改

我的一些XAML:

<Ellipse Name="SignalStatus" Height="16" Width="16" Margin="29,35,14.2,68.2">
        <Ellipse.Style>
            <Style TargetType="Ellipse">
                <!--<Setter Property="Fill" Value="Red"/> -->
                <Style.Triggers>
                    <!--SignalStatus "Unknown" -->
                    <DataTrigger Binding="{Binding SignalStatus, Converter={StaticResource IntToSignalStatus} }" Value="Unknown">
                        <Setter Property="Fill" Value="Magenta"/>
                    </DataTrigger>
                    <!--SignalStatus "Permissive" -->
                    <DataTrigger Binding="{Binding SignalStatus, Converter={StaticResource IntToSignalStatus} }" Value="Permissive">
                        <Setter Property="Fill" Value="Green"/>
                    </DataTrigger>
                    <!--SignalStatus "Restrictive" -->
                    <DataTrigger Binding="{Binding SignalStatus, Converter={StaticResource IntToSignalStatus} }" Value="Restrictive">
                        <Setter Property="Fill" Value="Red"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Ellipse.Style>
    </Ellipse>

转换器:

public class IntToSignalStatus : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return SignalStatus.Unknown;

        switch (value.ToString())
        {
            case "0":
                return SignalStatus.Restrictive;

            case "1":

                return SignalStatus.Permissive;

            default:
                break;
        }

        return PlatformSkip.Unknown;

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

在规范文档中,他们希望默认情况下在控件上设置Red color

如何为ellipse定义默认填充颜色(红色)?

PS:我是初学者,WPF&amp; C#编程

2 个答案:

答案 0 :(得分:1)

您的转换器应返回RestrictiveFill的{​​{1}}属性设置为Ellipse。这将触发您的上一次Red

DataTrigger

仅当转换器既不返回<DataTrigger Binding="{Binding SignalStatus, Converter={StaticResource IntToSignalStatus} }" Value="Restrictive"> <Setter Property="Fill" Value="Red"/> </DataTrigger> Unknown也不返回Permissive时,您的默认(未注释)设置器才会适用。

答案 1 :(得分:0)

XAML

<Ellipse Fill="{Binding MyColor}"></Ellipse>

MODEL

private string _myColor = "Red";

public string MyColor
{
    get { return _myColor; }
    set
    {
        _myColor = value;
        OnPropertyChanged("");
    }
}