首页 > 解决方案 > Xamarin Forms 绑定 - 拦截绑定值并更改它

问题描述

我有一个简单的组合自定义控件,它显示设置为绑定ControlText属性的文本。在下面的示例中,您可以看到单击按钮时控件会更新。

在此处输入图像描述

如何更改代码,以便控件显示的标签获取发送给它的任何内容并将其转换为全大写?

所以与其显示...

计数=5

它会显示...

计数=5

在这个简单的示例中,可以利用IValueConverter来完成此操作,但我希望看到一个不同的实现,用于我需要实现的更复杂的示例。 我正在寻找一种解决方案,它拦截后面代码中设置的值,对其进行转换,并将其设置为自定义控件的 ControlText 属性。

SimpleControl.xaml.cs

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SimpleControl : ContentView
{
    public SimpleControl ()
    {
        InitializeComponent ();
    }

    public static readonly BindableProperty ControlTextProperty = BindableProperty.Create(
                                           propertyName: nameof(ControlText),
                                           returnType: typeof(string),
                                           declaringType: typeof(SimpleControl),
                                           defaultBindingMode: BindingMode.TwoWay,
                                           defaultValue: "Hello World");

    public string ControlText
    {
        get { return (string)base.GetValue(ControlTextProperty); }
        set { base.SetValue(ControlTextProperty, value); }
    }
}

另外,我希望在运行时会命中这个断点,但代码永远不会停止。我正在从 SimplePageModel 设置属性,所以我觉得奇怪的是这从来没有被击中。有人也可以向我解释一下吗?

在此处输入图像描述

简单控制.xaml

<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App7.SimpleControl"
             x:Name="this">
    <ContentView.Content>
        <StackLayout Margin="100">
            <Label Text="{Binding Source={x:Reference this}, Path=ControlText}" />
        </StackLayout>
    </ContentView.Content>
</ContentView>

简单页面.xaml

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:App7"
             x:Class="App7.SimplePage">
    <ContentPage.Content>
        <StackLayout>
            <local:SimpleControl ControlText="{Binding ControlText}" />

            <Button Text="Update Control"
                Command="{Binding UpdateControl}" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

SimplePageModel.cs(利用 FreshMVVM)

public class SimplePageModel : FreshBasePageModel
{
    public SimplePageModel() { }

    private int _index;

    public string ControlText { get; set; }

    public Command UpdateControl
    {
        get
        {
            return new Command((t) =>
            {
                ControlText = $"Count = {++_index}";
            });
        }
    }

    public override void Init(object initData)
    {
        ControlText = $"Count = 0";

        base.Init(initData);
    }
}

标签: xamarinxamarin.formsfreshmvvm

解决方案


您也可以为此目的使用触发器,因为它不太清楚后台的想法是什么,我只是建议它可能会有所帮助: https ://docs.microsoft.com/en-us/xamarin/xamarin-表单/应用程序基础/触发器


推荐阅读