gpt4 book ai didi

Xamarin Forms 绑定(bind) - 拦截绑定(bind)值并更改它

转载 作者:行者123 更新时间:2023-12-05 07:22:01 25 4
gpt4 key购买 nike

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

enter image description here

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

所以不是显示...

计数=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 的属性,所以我觉得很奇怪,这从来没有被击中过。有人也可以向我解释一下吗?

enter image description here

SimpleControl.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>

SimplePage.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);
}
}

最佳答案

您也可以为此目的使用触发器,因为它不太清楚背景中的想法是什么,我只是建议它会有所帮助: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/triggers

关于Xamarin Forms 绑定(bind) - 拦截绑定(bind)值并更改它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56669930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com