我正在努力弄清楚我認爲應該是非常基本的東西,我希望有人能幫助我。Xamarin依賴綁定
我試圖根據數據是否提供給它來使自定義控件可見。
例如: 我有一個使用自定義控制如下主要頁面:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:controls="clr-namespace:XamarinDependantProperty.Controls;assembly=XamarinDependantProperty"
x:Class="XamarinDependantProperty.Pages.MainPage">
<ContentPage.Padding>
<OnPlatform x:TypeArguments="Thickness">
<On Platform="iOS" Value="0,20,0,0"/>
</OnPlatform>
</ContentPage.Padding>
<StackLayout>
<Label Text="Welcome to Xamarin Forms!" VerticalOptions="Center" HorizontalOptions="Center" />
<controls:CustomEntry TextValue="Test" VerticalOptions="Center" HorizontalOptions="Center"></controls:CustomEntry>
</StackLayout>
</ContentPage>
自定義控件如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XamarinDependantProperty.Controls.CustomEntry" IsVisible="{Binding TextIsVisible}">
<StackLayout>
<Label Text="{Binding TextIsVisible}" />
<Label Text="{Binding TextValue}" />
</StackLayout>
</ContentView>
而後面的代碼如下:
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace XamarinDependantProperty.Controls
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CustomEntry : ContentView
{
public CustomEntry()
{
InitializeComponent();
BindingContext = this;
}
public string TextValue
{
get { return (string)GetValue(TextValueProperty); }
set { SetValue(TextValueProperty, value); }
}
public static BindableProperty TextValueProperty = BindableProperty.Create(nameof(TextValue), typeof(string), typeof(CustomEntry));
public bool TextIsVisible => !String.IsNullOrEmpty(TextValue);
}
}
如果我將CustomEntry的TextValue設置爲「Test」,則輸出是:
歡迎來到Xamarin Forms!
假
測試
如果我把一個空字符串,那麼就沒有輸出,應用程序啓動,但不顯示任何內容。
如果我設置了TextValueProperty的默認值設置爲null,則輸出爲:
歡迎Xamarin形式!
從看來,當我設置TextValue,該TextIsVisible值在第一結合(ISVISIBLE)的工作,即使第二個結合(文本)輸出假的,但爲什麼是假的產出?
如果我沒有提供一個值,但我沒有告訴它null是一個可接受的空值,那麼它就完全搞砸了,但它並沒有對此提出任何意見。沒有錯誤,沒有輸出,什麼都沒有。有沒有辦法看到出現問題? (在iPhone模擬器上測試)
然後,如果我將這個概念從這種測試情境中解放出來並將其應用到實際情況中。然後設置TextValue和輸出TextIsVisible仍然是錯誤的,但它不顯示。
我在做什麼錯?我不瞭解什麼?
您需要在TextValue'setter'上爲'TextIsVisible'提升'NotificationChanged'。 –
@JesusAngulo您能詳細解釋一下嗎? –
我已經更新了我的答案 –