【问题标题】:Binding with IValueConverter does not work与 IValueConverter 绑定不起作用
【发布时间】:2015-09-21 16:32:05
【问题描述】:

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

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;
    }
}

调试输出没有出现,颜色也没有改变。我没看出有什么问题。

【问题讨论】:

  • 没有a good, minimal, complete code example,就无法说出问题所在。我会说,从您的代码示例看来,您正在绑定到实际上不在您的 UI 中的 Label 实例(即您动态创建它并且不将其附加到任何地方),并且您绑定到错误属性路径(应该是“TextColor”,而不是“TheTextColor”)。
  • 这是代码的简短版本。我在代码上不使用t send here, I have another UIs,viewModel 中的其他属性工作正常,例如 TextProperty。 Label 中的文本是黑色的,因此转换器的条件和转换器没有t work. Above this binding I have: myLabel.SetBinding(Label.TextProperty, "TheNames");` 它工作正常...
  • 请阅读我提供的链接以了解“良好、最小完整代码示例”的含义,以及有关以下方面的信息为什么需要这样的代码示例。请阅读stackoverflow.com/help/how-to-ask,了解有关如何以清晰、可回答的方式提出问题的更多信息。

标签: c# binding xamarin.forms ivalueconverter textcolor


【解决方案1】:

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

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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多