首页 > 解决方案 > 如何访问嵌入在自定义控件中的用户修改值?

问题描述

如何访问嵌入在自定义控件中的用户修改值?

我有一个自定义控件:

<ContentView
    x:Class="MyNamspce.LabelValuePair"
    x:Name="ParentControl"
    mc:Ignorable="d">
    <ContentView.Content>
        <StackLayout>
            ...
            <Entry Text="{Binding Source={x:Reference ParentControl}, Path=ValueText}" />
        </StackLayout>
    </ContentView.Content>
</ContentView>

以下是我如何使用自定义控件:

<local:LabelValuePair
    ...
    ValueText="{Binding ., Converter={StaticResource PairTemplateToEntryConverter}}" />

这是支持数据结构:

type LabelEntryPair2 () =

    member val LabelFGColor = "" with get,set
    member val Label        = "" with get,set
    member val EntryValue   = "" with get,set
    member val ValueFGColor = "" with get,set

我成功地将值加载到自定义控件中。但是,在用户修改这些值后,我无法检索它们。

笔记:

每次我通过用户界面编辑条目控件值时都会触发ValueText属性的设置器:

值转换器PairTemplateToEntryConverter在我编辑条目值后从不调用ConvertBack方法。

public static BindableProperty ValueTextProperty = BindableProperty.Create(
                    propertyName: "ValueText",
                    returnType: typeof(string),
                    declaringType: typeof(LabelValuePair),
                    defaultValue: "",
                    defaultBindingMode: BindingMode.TwoWay);

    public string ValueText
    {
        get { return (string)GetValue(ValueTextProperty); }
        set { SetValue(ValueTextProperty, value); } // ** This is being triggered every time **
    }

但是,我无法在实际数据结构(即LabelEntryPair2)上获取这些更新

总之,如何访问嵌入在自定义控件中的用户修改值?

标签: xamarin.forms

解决方案


这里的问题是:

ValueText="{Binding ., Converter={StaticResource PairTemplateToEntryConverter}}"

因此 ValueText 被绑定到整个列表项对象,然后使用转换器从对象的字符串属性中提取字符串。这是一种不寻常的方法,我认为没有真正的原因。相反,为什么不直接绑定到对象上的属性呢?> 例如:

ValueText="{Binding EntryValue}"

推荐阅读