繁体   English   中英

与 IValueConverter 绑定不起作用

[英]Binding with IValueConverter does not work

我正在尝试从TextColor的标签绑定ViewCell

Label myLabel = new Label { Text = "SomeText" };

myLabel.SetBinding(Label.TextColorProperty,
    new Binding("TheTextColor", BindingMode.TwoWay, new LabelTextColorConverter()));

这是转换器:

public class LabelTextColorConverter : IValueConverter
{
    public bool OldValue { get; set; }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        OldValue = (bool) value;
        Debug.WriteLine("asdadasdsadsada");
        if ((bool)value)
            return Color.Red;
        else
            return Color.Silver;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Debug.WriteLine("qwqweqewqeeqe");
        return OldValue;
    }
}

调试输出不会出现,颜色也不会改变。 我看不出有什么不对。

为什么你需要双向绑定? 我认为没有必要。

myLabel.SetBinding(Label.TextColorProperty, new Binding("TheTextColor", BindingMode.OneWay, new LabelTextColorConverter()));

然后:

public class LabelTextColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        bool val = (bool)value;

        if (val)
            return Color.Red;
        else
            return Color.Silver;
    }

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

...它应该可以正常工作。 还要确保您为页面/控件正确设置了 BindingContext。

暂无
暂无

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

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