Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 与IValueConverter绑定不起作用_C#_Binding_Xamarin.forms_Ivalueconverter_Textcolor - Fatal编程技术网

C# 与IValueConverter绑定不起作用

C# 与IValueConverter绑定不起作用,c#,binding,xamarin.forms,ivalueconverter,textcolor,C#,Binding,Xamarin.forms,Ivalueconverter,Textcolor,我正在尝试从ViewCell上的标签绑定TextColor: Label myLabel = new Label { Text = "SomeText" }; myLabel.SetBinding(Label.TextColorProperty, new Binding("TheTextColor", BindingMode.TwoWay, new LabelTextColorConverter())); 这是转换器: public class LabelTextColorConve

我正在尝试从
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;
    }
}

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

为什么需要双向装订?我认为没有必要

myLabel.SetBinding(Label.TextColorProperty,新绑定(“TheTextColor”,BindingMode.OneWay,新LabelTextColorConverter());
然后:

公共类LabelTextColorConverter:IValueConverter
{
公共对象转换(对象值、类型targetType、对象参数、System.Globalization.CultureInfo区域性)
{
布尔值=(布尔)值;
if(val)
返回颜色:红色;
其他的
返回颜色:银色;
}
公共对象转换回(对象值、类型targetType、对象参数、System.Globalization.CultureInfo区域性)
{
抛出新的NotImplementedException();
}
}

。。。它应该很好用。还要确保您为页面/控件正确设置了BindingContext。

如果没有设置,就不可能说出问题所在。我要说的是,从您的代码示例来看,您似乎绑定到了一个实际不在UI中的
标签
实例(即,您动态创建它,但没有将其附加到任何地方),并且绑定到了错误的属性路径(应该是“TextColor”,而不是“TheTextColor”)。这是代码的一个简短版本。我不在这里发送,我在代码上有另一个UI,viewModel中的其他属性工作正常,比如TextProperty。标签中的文本为黑色,因此conditional on converter和converter不起作用。在这个绑定之上,我有:myLabel.SetBinding(Label.TextProperty,“TheNames”);`它工作良好…请阅读我提供的链接,了解“好的、最少的、完整的代码示例”的含义,以及为什么需要这样的代码示例的信息。请阅读更多关于如何以清晰、负责的方式提出问题的信息。